<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');


date_default_timezone_set("Asia/Calcutta");

$fromdate = date('Y-m-d H:i:s');


include('inc/config.php');
header('Content-Type: application/json');

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

    
    if ($action === 'Create' || $action === 'Update') {
        
        $uniqueID = mysqli_real_escape_string($conn, $_POST['UniqueID'] ?? mt_rand(100000, 999999));
        $doctorID = mysqli_real_escape_string($conn, $_POST['DoctorID'] ?? '');
		$name = mysqli_real_escape_string($conn, $_POST['PatientName'] ?? '');
        $phone = mysqli_real_escape_string($conn, $_POST['Phone'] ?? '');
        $dob = mysqli_real_escape_string($conn, $_POST['DOB'] ?? '');
        $specialNote = mysqli_real_escape_string($conn, $_POST['SpecialNote'] ?? '');
        $gender = mysqli_real_escape_string($conn, $_POST['Gender'] ?? ''); 
        $currentMedicines = mysqli_real_escape_string($conn, $_POST['CurrentMedicines'] ?? '');
        $id = mysqli_real_escape_string($conn, $_POST['id'] ?? null);
        $useridnew = mysqli_real_escape_string($conn, $_POST['useridnew'] ?? null);
        $rolenew = mysqli_real_escape_string($conn, $_POST['rolenew'] ?? null);
        function generateHospitalPatientID($conn) {
    // Get the current year
    $currentYear = date("Y");
    $yearShort = substr($currentYear, -2);

    // Query to get the count of patients registered in the current year
    $query = "SELECT COUNT(*) FROM Patients";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_row($result);
    
    // Increment the count to get the next sequential number
    $sequentialNumber = str_pad($row[0] + 1, 5, "0", STR_PAD_LEFT);

    // Combine year and sequential number to form the Patient ID
    $patientID = $sequentialNumber;

    return $patientID;
}



$uniquePatientID = generateHospitalPatientID($conn);
        
        if (empty($doctorID) ||empty($name) || empty($phone)) {
            echo json_encode(['status' => 'Error', 'message' => 'Doctor and Patient and Phone are required']);
            exit;
        }

        
        $profilePhoto = null;
        if (isset($_FILES['ProfilePhoto']) && $_FILES['ProfilePhoto']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = 'uploads/';
            $fileName = uniqid() . '_' . basename($_FILES['ProfilePhoto']['name']);
            $filePath = $uploadDir . $fileName;

            if (move_uploaded_file($_FILES['ProfilePhoto']['tmp_name'], $filePath)) {
                $profilePhoto = $fileName;
            }
        }

        if ($action === 'Create') {
            
            $stmt = $conn->prepare("SELECT * FROM Patients WHERE Phone = ?");
    $stmt->bind_param("s", $phone);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        echo json_encode(['status' => 'Duplicate', 'message' => 'Phone number already exists']);
        exit;
    }

    // Insert query depending on whether ProfilePhoto is available
    if ($profilePhoto) {
        $insertQuery = "INSERT INTO Patients 
            (DoctorID,UniqueID, PatientName, Phone, DOB, SpecialNote, JoiningDate, Status, ProfilePhoto, Gender, CurrentMedicines, created_at,AdminId, UserId,UserRole) 
            VALUES (?,?, ?, ?, ?, ?, ?, 'Active', ?, ?, ?, ?, ?, ?, ?)";
    } else {
        $insertQuery = "INSERT INTO Patients 
            (DoctorID,UniqueID, PatientName, Phone, DOB, SpecialNote, JoiningDate, Status, Gender, CurrentMedicines, created_at,AdminId, UserId,UserRole) 
            VALUES (?,?, ?, ?, ?, ?, ?, 'Active', ?, ?, ?, ?, ?, ?)";
    }

    $stmt = $conn->prepare($insertQuery);

    // Validate if the statement was prepared successfully
    if ($stmt === false) {
        echo json_encode(['status' => 'Error', 'message' => $conn->error]);
        exit;
    }

    // Bind parameters based on query
    if ($profilePhoto) {
        $stmt->bind_param("ssssssssssssss",$doctorID,$uniquePatientID,$name,$phone,$dob,$specialNote,$fromdate,$profilePhoto,$gender,$currentMedicines,$fromdate,$useridnew,$useridnew,$rolenew);
    } else {
        $stmt->bind_param("sssssssssssss",$doctorID,$uniquePatientID,$name,$phone,$dob,$specialNote,$fromdate,$gender,$currentMedicines,$fromdate,$useridnew,$useridnew,$rolenew);
    }
    
    

    // Execute the statement
    if ($stmt->execute()) {
        echo json_encode(['status' => 'Create']);
    } else {
        echo json_encode(['status' => 'Error', 'message' => $stmt->error]);
    }
            }
        elseif ($action === 'Update' && $id) {
            
            if ($profilePhoto) {
                $stmt = $conn->prepare("SELECT ProfilePhoto FROM Patients WHERE PatientID = ?");
                $stmt->bind_param("i", $id);
                $stmt->execute();
                $result = $stmt->get_result();

                if ($result->num_rows > 0) {
                    $row = $result->fetch_assoc();
                    $oldPhoto = $row['ProfilePhoto'];
                    if ($oldPhoto && file_exists("uploads/$oldPhoto")) {
                        unlink("uploads/$oldPhoto");
                    }
                }
            }

            $updateQuery = "UPDATE Patients SET DoctorID = ?,PatientName = ?, Phone = ?, DOB = ?, SpecialNote = ?, updated_at = ?, Gender = ?, CurrentMedicines = ?"
                . ($profilePhoto ? ", ProfilePhoto = ?" : "")
                . " WHERE PatientID = ?";

            $stmt = $conn->prepare($updateQuery);

            if ($profilePhoto) {
                $stmt->bind_param("sssssssssi",$doctorID, $name, $phone, $dob, $specialNote, $fromdate, $gender, $currentMedicines, $profilePhoto, $id);
            } else {
                $stmt->bind_param("ssssssssi", $doctorID,$name, $phone, $dob, $specialNote, $fromdate, $gender, $currentMedicines, $id);
            }

            if ($stmt->execute()) {
                echo json_encode(['status' => 'Update']);
            } else {
                echo json_encode(['status' => 'Error', 'message' => $stmt->error]);
            }
        }
    }

    // Select action
    if ($action === 'Select' && isset($_POST['id'])) {
        $id = $_POST['id'];
        $stmt = $conn->prepare("SELECT * FROM Patients WHERE PatientID = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $row['ProfilePhoto'] = !empty($row['ProfilePhoto']) ? 'uploads/' . $row['ProfilePhoto'] : null;
            echo json_encode($row);
        } else {
            echo json_encode(['status' => 'Error', 'message' => 'Record not found']);
        }
    }

    // Delete action
    if ($action === 'Delete' && isset($_POST['id'])) {
        $id = $_POST['id'];
        $stmt = $conn->prepare("SELECT ProfilePhoto FROM Patients WHERE PatientID = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            if (!empty($row['ProfilePhoto']) && file_exists("uploads/" . $row['ProfilePhoto'])) {
                unlink("uploads/" . $row['ProfilePhoto']);
            }

            $stmt = $conn->prepare("DELETE FROM Patients WHERE PatientID = ?");
            $stmt->bind_param("i", $id);

            if ($stmt->execute()) {
                echo json_encode(['status' => 'Delete', 'message' => 'Record deleted successfully']);
            } else {
                echo json_encode(['status' => 'Error', 'message' => $stmt->error]);
            }
        } else {
            echo json_encode(['status' => 'Error', 'message' => 'Record not found']);
        }
    }

    // Status Change action
    if ($action === 'StatusChange' && isset($_POST['id'])) {
        $id = $_POST['id'];
        $stmt = $conn->prepare("SELECT status FROM Patients WHERE PatientID = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $new_status = $row['status'] === 'Active' ? 'Inactive' : 'Active';

            $stmt = $conn->prepare("UPDATE Patients SET status = ? WHERE PatientID = ?");
            $stmt->bind_param("si", $new_status, $id);

            if ($stmt->execute()) {
                echo json_encode(['status' => $new_status]);
            } else {
                echo json_encode(['status' => 'Error', 'message' => $stmt->error]);
            }
        } else {
            echo json_encode(['status' => 'Error', 'message' => 'Record not found']);
        }
    }
}


mysqli_close($conn);
?>
