<?php
session_start();
include_once '../config.php';

$user_id = $_SESSION['Admin']['id'];
$CurrDate = date('Y-m-d');
$CreatedDate = date('Y-m-d');
$CreatedTime = date('h:i a');

// Simple sanitizer
function clean($v) {
    return trim(addslashes($v ?? ''));
}

$action = $_REQUEST['action'] ?? '';

/* ============================================================
   🔵 COMMON SUCCESS FUNCTION
============================================================ */
function successRedirect($MrdNo, $VisitDate) {
    echo "
    <script src='../sweetalert-dev.js'></script>
    <link rel='stylesheet' href='../sweetalert.css'>
    <script>
        setTimeout(function () {
            swal({
                title: 'Success!',
                text: 'Record Saved Successfully!',
                type: 'success'
            }, function(){
                window.location.href='../patientdetailform.php?mrd={$MrdNo}&visitdate={$VisitDate}';
            });
            setTimeout(function() {
                window.location.href='../patientdetailform.php?mrd={$MrdNo}&visitdate={$VisitDate}';
            }, 1000);
        });
    </script>";
    exit;
}

/* ============================================================
   🔵 SAVE ENTRY
============================================================ */
if ($action == 'Save') {

    /* -------------------------------------------------
       🔹 Collect All Inputs (Cleaned)
    ------------------------------------------------- */
    $MrdNo = clean($_POST['MrdNo']);
    $PatientId = clean($_POST['PatientId']);
    $VisitDate = clean($_POST['VisitDate2']);
    $VisitTime = clean($_POST['VisitTime']);
    $Fname = clean($_POST['Fname']);
    $Mname = clean($_POST['Mname']);
    $Lname = clean($_POST['Lname']);
    $Age = clean($_POST['Age']);
    $Gender = clean($_POST['Gender']);
    $Phone = clean($_POST['Phone']);
    $EmailId = clean($_POST['EmailId']);
    $Address = clean($_POST['Address']);
    $City = clean($_POST['City']);
    $RelativeComes = clean($_POST['RelativeComes']);
    $RelativeName = clean($_POST['RelativeName']);
    $Relationship = clean($_POST['Relationship']);
    $PatientWilling = clean($_POST['PatientWilling']);
    $Prognosis = clean($_POST['Prognosis']);
    $DSH = clean($_POST['DSH']);
    $Admission = clean($_POST['Admission']);
    $FollowUp = clean($_POST['FollowUp']);
    $Irregular = clean($_POST['Irregular']);
    $Medication = clean($_POST['Medication']);
    $Notes = clean($_POST['Notes']);
    $Notorious = clean($_POST['Notorious']);
    $NotoriousChk = clean($_POST['NotoriousChk']);
    $FollowUpDate = clean($_POST['FollowUpDate']);
    $Remark = clean($_POST['Remark']);
    $SpecialNote = clean($_POST['SpecialNote']);
    $RefBy = clean($_POST['RefBy']);
    $MarritalStatus = clean($_POST['MarritalStatus']);
    $StrictSupervision = clean($_POST['StrictSupervision']);
    $Diagnosis = clean($_POST['Diagnosis']);
    $PatientName = clean($_POST['PatientName']);
    $NewPhone = clean($_POST['NewPhone']);
    $NewName = clean($_POST['NewName']);
    $Duration = clean($_POST['Duration']);

    // Comorbidities
    $DM = clean($_POST['DM']);
    $HT = clean($_POST['HT']);
    $IHD = clean($_POST['IHD']);
    $PILES = clean($_POST['PILES']);
    $Thyroid = clean($_POST['Thyroid']);
    $Telugu = clean($_POST['Telugu']);
    $Other = clean($_POST['Other']);
    $OtherTxt = clean($_POST['OtherTxt']);

    // Investigation
    $ChkBlood = clean($_POST['ChkBlood']);
    $TxtBlood = clean($_POST['TxtBlood']);
    $ChkCT = clean($_POST['ChkCT']);
    $TxtCT = clean($_POST['TxtCT']);
    $ChkMRI = clean($_POST['ChkMRI']);
    $TxtMRI = clean($_POST['TxtMRI']);
    $ChkUSG = clean($_POST['ChkUSG']);
    $TxtUSG = clean($_POST['TxtUSG']);
    $ChkOthers = clean($_POST['ChkOthers']);
    $TxtOthers = clean($_POST['TxtOthers']);
    $Eeg = clean($_POST['Eeg']);
    $TxtEeg = clean($_POST['TxtEeg']);

    $PrevTreatment = clean($_POST['PrevTreatment']);
    $Language = clean($_POST['Language']);
    $ChkPrevTreat = clean($_POST['ChkPrevTreat']);
    $ChkDiagnosis = clean($_POST['ChkDiagnosis']);
    $ChkAdvice = clean($_POST['ChkAdvice']);
    $ChkSpecialNote = clean($_POST['ChkSpecialNote']);
    $NameUnder = clean($_POST['NameUnder']);
    $FontStyle = clean($_POST['FontStyle']);
    $ptnotes = clean($_POST['ptnotes']);
    $ptnotesdate = date('Y-m-d');
    $Status = 1;

    /* ============================================================
       🔹 Update Language Always
    ============================================================ */
    $conn->query("UPDATE tbl_patients SET Language='$Language' WHERE MrdNo='$MrdNo'");

    /* ============================================================
       🔹 Check if Patient Exists
    ============================================================ */
    $r = getRow("SELECT id FROM tbl_patients WHERE MrdNo='$MrdNo'");

    if ($r > 0) {

        // Update basic patient info
        $conn->query("UPDATE tbl_patients SET 
            ptnotes='$ptnotes',
            ptnotesdate='$ptnotesdate',
            Age='$Age',
            Phone='$Phone',
            EmailId='$EmailId',Address='$Address'
            WHERE MrdNo='$MrdNo'
        ");

        // Update Name
        if ($NewName != '') {
            $conn->query("UPDATE tbl_patients SET PatientName='$NewName' WHERE MrdNo='$MrdNo'");
            $conn->query("INSERT INTO tbl_patient_new_records (MrdNo,OldName,Name,CreatedDate,CreatedTime)
                          VALUES ('$MrdNo','$PatientName','$NewName','$CreatedDate','$CreatedTime')");
        }

        // Update Phone
        if ($NewPhone != '') {
            $conn->query("UPDATE tbl_patients SET Phone='$NewPhone' WHERE MrdNo='$MrdNo'");
            $conn->query("INSERT INTO tbl_patient_new_records (MrdNo,OldPhone,Phone,CreatedDate,CreatedTime)
                          VALUES ('$MrdNo','$Phone','$NewPhone','$CreatedDate','$CreatedTime')");
        }
    }
    else {
        // CREATE NEW PATIENT
        $conn->query("INSERT INTO tbl_patients 
            (ptnotes,ptnotesdate,MarritalStatus,srno,MrdNo,PatientName,Fname,Mname,Lname,Gender,Age,Phone,
             EmailId,City,Address,RefBy,Status,CreatedBy,CreatedDate)
        VALUES 
            ('$ptnotes','$ptnotesdate','$MarritalStatus','$MrdNo','$MrdNo','$PatientName',
             '$Fname','$Mname','$Lname','$Gender','$Age','$Phone',
             '$EmailId','$City','$Address','$RefBy','$Status','$user_id','$CreatedDate')
        ");
    }

    /* ============================================================
       🔹 Visits — Create if not exists
    ============================================================ */
    $visitRow = getRow("SELECT id FROM tbl_visits WHERE MrdNo='$MrdNo' AND VisitDate='$VisitDate'");

    if (!$visitRow) {
        $vis = getRecord("SELECT MAX(VisitNo) AS VisitNo FROM tbl_visits WHERE MrdNo='$MrdNo'");
        $VisitNo = $vis['VisitNo'] + 1;

        $conn->query("INSERT INTO tbl_visits (MrdNo,PatientName,VisitDate,VisitNo)
                      VALUES ('$MrdNo','$PatientName','$VisitDate','$VisitNo')");
    }

    /* ============================================================
       🔹 Consultant — Insert or Update
    ============================================================ */

    $cRow = getRecord("SELECT * FROM tbl_consultant WHERE MrdNo='$MrdNo' AND VisitDate='$VisitDate'");

    if ($cRow) {

        // UPDATE
        $PostId = $cRow['id'];

        $conn->query("UPDATE tbl_consultant SET FontStyle='$FontStyle',
            NameUnder='$NameUnder',
            Diagnosis='$Diagnosis',
            StrictSupervision='$StrictSupervision',
            Duration='$Duration',
            MarritalStatus='$MarritalStatus',
            RefBy='$RefBy',
            Fname='$Fname',Mname='$Mname',Lname='$Lname',
            PatientName='$PatientName',Age='$Age',Gender='$Gender',
            Phone='$Phone',EmailId='$EmailId',Address='$Address',City='$City',
            RelativeComes='$RelativeComes',RelativeName='$RelativeName',Relationship='$Relationship',
            PatientWilling='$PatientWilling',Prognosis='$Prognosis',DSH='$DSH',Admission='$Admission',
            FollowUp='$FollowUp',Irregular='$Irregular',Medication='$Medication',
            Notes='$Notes',NotoriousChk='$NotoriousChk',Notorious='$Notorious',
            FollowUpDate='$FollowUpDate',Remark='$Remark',SpecialNote='$SpecialNote',
            Status='1',
            DM='$DM',HT='$HT',IHD='$IHD',PILES='$PILES',Thyroid='$Thyroid',Telugu='$Telugu',
            ChkBlood='$ChkBlood',TxtBlood='$TxtBlood',
            ChkCT='$ChkCT',TxtCT='$TxtCT',ChkMRI='$ChkMRI',TxtMRI='$TxtMRI',
            ChkUSG='$ChkUSG',TxtUSG='$TxtUSG',ChkOthers='$ChkOthers',TxtOthers='$TxtOthers',
            Other='$Other',PrevTreatment='$PrevTreatment',Eeg='$Eeg',TxtEeg='$TxtEeg',
            OtherTxt='$OtherTxt',Language='$Language',ChkPrevTreat='$ChkPrevTreat',
            ChkDiagnosis='$ChkDiagnosis',ChkAdvice='$ChkAdvice',ChkSpecialNote='$ChkSpecialNote'
        WHERE id='$PostId'");
    }

    else {

        // INSERT
         $sql = "INSERT INTO tbl_consultant
            (FontStyle,NameUnder,Diagnosis,StrictSupervision,Duration,MarritalStatus,RefBy,MrdNo,PatientId,VisitDate,VisitTime,
             Fname,Mname,Lname,PatientName,Age,Gender,Phone,EmailId,Address,City,RelativeComes,RelativeName,
             Relationship,PatientWilling,Prognosis,DSH,Admission,FollowUp,Irregular,Medication,Notes,
             NotoriousChk,Notorious,FollowUpDate,Remark,SpecialNote,CreatedDate,CreatedTime,Status)
         VALUES 
            ('$FontStyle','$NameUnder','$Diagnosis','$StrictSupervision','$Duration','$MarritalStatus','$RefBy','$MrdNo','$PatientId',
             '$VisitDate','$VisitTime','$Fname','$Mname','$Lname','$PatientName','$Age','$Gender','$Phone',
             '$EmailId','$Address','$City','$RelativeComes','$RelativeName','$Relationship','$PatientWilling',
             '$Prognosis','$DSH','$Admission','$FollowUp','$Irregular','$Medication','$Notes','$NotoriousChk',
             '$Notorious','$FollowUpDate','$Remark','$SpecialNote','$CreatedDate','$CreatedTime','1')";
        $conn->query($sql);

        $PostId = $conn->lastInsertId();

        // Add comorbid + other fields
        $conn->query("UPDATE tbl_consultant SET 
            FontStyle='$FontStyle',DM='$DM',HT='$HT',IHD='$IHD',PILES='$PILES',Thyroid='$Thyroid',Telugu='$Telugu',
            ChkBlood='$ChkBlood',TxtBlood='$TxtBlood',ChkCT='$ChkCT',TxtCT='$TxtCT',
            ChkMRI='$ChkMRI',TxtMRI='$TxtMRI',ChkUSG='$ChkUSG',TxtUSG='$TxtUSG',ChkOthers='$ChkOthers',
            TxtOthers='$TxtOthers',Other='$Other',PrevTreatment='$PrevTreatment',Eeg='$Eeg',TxtEeg='$TxtEeg',
            OtherTxt='$OtherTxt',Language='$Language',ChkPrevTreat='$ChkPrevTreat',
            ChkDiagnosis='$ChkDiagnosis',ChkAdvice='$ChkAdvice',ChkSpecialNote='$ChkSpecialNote',
            NameUnder='$NameUnder'
        WHERE id='$PostId'");
    }

    /* ============================================================
       🔹 TREATMENTS (Reset + Insert)
    ============================================================ */

    $conn->query("DELETE FROM tbl_consultant_treatments 
                  WHERE MrdNo='$MrdNo' AND VisitDate='$VisitDate'");

    $TreatName1 = $_POST['TreatName1'] ?? [];

    if (count($TreatName1) > 0) {
        foreach ($TreatName1 as $i => $tname) {

            if (trim($tname) == '') continue;

            $TType  = clean($_POST['TreatType1'][$i]);
            $TDose  = clean($_POST['TreatDose1'][$i]);
            $TFreq  = clean($_POST['TreatFreq1'][$i]);
            $TDur   = clean($_POST['TreatDur1'][$i]);
            $TEye   = clean($_POST['TreatEye1'][$i]);

            $conn->query("INSERT INTO tbl_consultant_treatments
                (PostId,MrdNo,VisitDate,TreatType1,TreatName1,TreatDose1,TreatFreq1,TreatDur1,TreatEye1,Status)
                VALUES 
                ('$PostId','$MrdNo','$VisitDate','$TType','$tname','$TDose','$TFreq','$TDur','$TEye','1')");
        }
    }

    /* ============================================================
       🔹 Final success
    ============================================================ */
    successRedirect($MrdNo, $VisitDate);
}

/* ============================================================
   🔵 FIND FOLLOW UPDATE
============================================================ */
if ($action == 'findFollowDate') {
    $Duration = intval($_REQUEST['Duration']);
    $date = date('Y-m-d', strtotime("+{$Duration} days"));
    $day = date('D', strtotime($date));

    echo json_encode([
        "Status" => ($day == 'Sun') ? 0 : 1,
        "FollowDate" => $date
    ]);
    exit;
}

/* ============================================================
   🔵 PATIENT NAME/PHONE HISTORY
============================================================ */
if ($action == 'getUpRecordList') {

    $MrdNo = clean($_POST['MrdNo']);
    $rows = getList("SELECT * FROM tbl_patient_new_records WHERE MrdNo='$MrdNo'");

    if (!$rows) {
        echo "<h4 style='color:red;'>No Record Found!</h4>";
        exit;
    }

    echo "<tr><th>Name</th><th>Contact</th><th>Date</th></tr>";
    foreach ($rows as $r) {
        $dt = date("d/m/Y", strtotime($r['CreatedDate']));
        echo "<tr>
            <td>{$r['Name']}</td>
            <td>{$r['Phone']}</td>
            <td>{$dt}</td>
        </tr>";
    }
    exit;
}

/* ============================================================
   🔵 DELETE RECORD
============================================================ */
if ($action == 'deleteRecord') {

    $MrdNo = clean($_POST['MrdNo']);
    $VisitDate = clean($_POST['VisitDate']);

    // Backup then delete
    $conn->query("INSERT INTO tbl_consultant_delete SELECT * FROM tbl_consultant 
                  WHERE MrdNo='$MrdNo' AND VisitDate='$VisitDate'");

    $conn->query("INSERT INTO tbl_consultant_treatments_delete SELECT * FROM tbl_consultant_treatments 
                  WHERE MrdNo='$MrdNo' AND VisitDate='$VisitDate'");

    $conn->query("DELETE FROM tbl_consultant WHERE MrdNo='$MrdNo' AND VisitDate='$VisitDate'");
    $conn->query("DELETE FROM tbl_consultant_treatments WHERE MrdNo='$MrdNo' AND VisitDate='$VisitDate'");
    $conn->query("DELETE FROM tbl_visits WHERE MrdNo='$MrdNo' AND VisitDate='$VisitDate'");
    
    echo "1";
    exit;
}

?>
