<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
date_default_timezone_set("Asia/Calcutta"); // India time (GMT+5:30)

include('inc/config.php');

// Ensure JSON header for all responses
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? null;

    // Handle Select Action
    if ($action === 'Select') {
        $id = intval($_POST['id'] ?? 0);
        $query = "SELECT * FROM Reports WHERE ReportID = ?";
        if ($stmt = mysqli_prepare($conn, $query)) {
            mysqli_stmt_bind_param($stmt, 'i', $id);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);

            if ($result) {
                $data = mysqli_fetch_assoc($result);
                echo json_encode($data);
            } else {
                echo json_encode(['status' => 'Error', 'message' => 'Error fetching data: ' . mysqli_error($conn)]);
            }
            mysqli_stmt_close($stmt);
        }
        exit();
    }

    // Common variables
    $uniqueID = mysqli_real_escape_string($conn, $_POST['UniqueID'] ?? mt_rand(100000, 999999));
    $doctor_id = mysqli_real_escape_string($conn, $_POST['doctor_id'] ?? 0);
    $patient_id = mysqli_real_escape_string($conn, $_POST['patient_id'] ?? 0);
    $appointment_id = mysqli_real_escape_string($conn, $_POST['appointment_id'] ?? 0);
    $useridnew = mysqli_real_escape_string($conn, $_POST['useridnew'] ?? 0);
    $rolenew = mysqli_real_escape_string($conn, $_POST['rolenew'] ?? 0);
    
    $fromdate = date('Y-m-d H:i:s');
    $regdate = date('Y-m-d');

    // Handle file uploads
    $file_name = '';
    if (isset($_FILES['report_pdf']) && $_FILES['report_pdf']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = 'uploads/';
        $file_info = pathinfo($_FILES['report_pdf']['name']);
        $extension = strtolower($file_info['extension']);
        $allowed_extensions = ['pdf', 'docx', 'doc'];

        // Check for valid file extension
        if (!in_array($extension, $allowed_extensions)) {
            echo json_encode(['status' => 'Error', 'message' => 'Invalid file type.']);
            exit();
        }

        // Generate unique file name
        $file_name = time() . '_' . $file_info['basename'];
        $file_path = $upload_dir . $file_name;

        // Move uploaded file
        if (!move_uploaded_file($_FILES['report_pdf']['tmp_name'], $file_path)) {
            echo json_encode(['status' => 'Error', 'message' => 'Failed to upload the file.']);
            exit();
        }
    }

    // Handle Create Action
    if ($action === 'Create') {
        $sql_check = "SELECT * FROM Reports WHERE DoctorID = ? AND PatientID = ? AND AppointmentID = ?";
        if ($stmt_check = mysqli_prepare($conn, $sql_check)) {
            mysqli_stmt_bind_param($stmt_check, 'iii', $doctor_id, $patient_id, $appointment_id);
            mysqli_stmt_execute($stmt_check);
            mysqli_stmt_store_result($stmt_check);

            if (mysqli_stmt_num_rows($stmt_check) > 0) {
                echo json_encode(['status' => 'Duplicate', 'message' => 'Report already exists for this appointment.']);
            } else {
                $query = "INSERT INTO Reports (DoctorID, PatientID, AppointmentID, UniqueID, ReportPDF, ReportDate,AdminId, UserId, UserRole, CreatedAt)
                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                if ($stmt_insert = mysqli_prepare($conn, $query)) {
                    mysqli_stmt_bind_param($stmt_insert, 'iiisssssss', $doctor_id, $patient_id, $appointment_id, $uniqueID, $file_name,$regdate, $useridnew, $useridnew, $rolenew, $fromdate);
                    if (mysqli_stmt_execute($stmt_insert)) {
                        echo json_encode(['status' => 'Create', 'message' => 'Report created successfully.']);
                    } else {
                        echo json_encode(['status' => 'Error', 'message' => 'Failed to create report: ' . mysqli_error($conn)]);
                    }
                    mysqli_stmt_close($stmt_insert);
                }
            }
            mysqli_stmt_close($stmt_check);
        }
        exit();
    }

    // Handle Update Action
    if ($action === 'Update') {
        $id = intval($_POST['id']);
        $sql_check = "SELECT * FROM Reports WHERE DoctorID = ? AND PatientID = ? AND AppointmentID = ? AND ReportID != ?";
        if ($stmt_check = mysqli_prepare($conn, $sql_check)) {
            mysqli_stmt_bind_param($stmt_check, 'iiii', $doctor_id, $patient_id, $appointment_id, $id);
            mysqli_stmt_execute($stmt_check);
            mysqli_stmt_store_result($stmt_check);

            if (mysqli_stmt_num_rows($stmt_check) > 0) {
                echo json_encode(['status' => 'Duplicate', 'message' => 'Duplicate report found.']);
            } else {
                $query = "UPDATE Reports SET DoctorID = ?, PatientID = ?, AppointmentID = ?";
                if ($file_name) {
                    $query .= ", ReportPDF = ?";
                }
                $query .= " WHERE ReportID = ?";

                if ($stmt_update = mysqli_prepare($conn, $query)) {
                    if ($file_name) {
                        mysqli_stmt_bind_param($stmt_update, 'iiisi', $doctor_id, $patient_id, $appointment_id, $file_name, $id);
                    } else {
                        mysqli_stmt_bind_param($stmt_update, 'iiii', $doctor_id, $patient_id, $appointment_id, $id);
                    }

                    if (mysqli_stmt_execute($stmt_update)) {
                        echo json_encode(['status' => 'Update', 'message' => 'Report updated successfully.']);
                    } else {
                        echo json_encode(['status' => 'Error', 'message' => 'Failed to update report: ' . mysqli_error($conn)]);
                    }
                    mysqli_stmt_close($stmt_update);
                }
            }
            mysqli_stmt_close($stmt_check);
        }
        exit();
    }

    // Handle Delete Action
    if ($action === 'Delete') {
        $id = intval($_POST['id']);
        $photoQuery = "SELECT ReportPDF FROM Reports WHERE ReportID = ?";
        if ($stmt_select = mysqli_prepare($conn, $photoQuery)) {
            mysqli_stmt_bind_param($stmt_select, 'i', $id);
            mysqli_stmt_execute($stmt_select);
            $result = mysqli_stmt_get_result($stmt_select);

            if ($result && mysqli_num_rows($result) > 0) {
                $row = mysqli_fetch_assoc($result);
                if (!empty($row['ReportPDF'])) {
                    $filePath = 'uploads/' . $row['ReportPDF'];
                    if (file_exists($filePath)) {
                        unlink($filePath);
                    }
                }

                $deleteQuery = "DELETE FROM Reports WHERE ReportID = ?";
                if ($stmt_delete = mysqli_prepare($conn, $deleteQuery)) {
                    mysqli_stmt_bind_param($stmt_delete, 'i', $id);
                    if (mysqli_stmt_execute($stmt_delete)) {
                        echo json_encode(['status' => 'Delete', 'message' => 'Record deleted successfully']);
                    } else {
                        echo json_encode(['status' => 'Error', 'message' => 'Error deleting record']);
                    }
                    mysqli_stmt_close($stmt_delete);
                }
            }
            mysqli_stmt_close($stmt_select);
        } else {
            echo json_encode(['status' => 'Error', 'message' => 'Record not found']);
        }
        exit();
    }
}
?>
