<?php
session_start();
if (!isset($_SESSION['staff_logged_in'])) { header("Location: login.php"); exit(); }
include '../db_connect.php';
date_default_timezone_set('Asia/Kolkata');

// Link to the FPDF library (Ensure this path is correct)
require('../admin/fpdf/fpdf.php'); 

$msg = "";
$whatsapp_btn = ""; // Variable to hold the button

if (isset($_POST['save_entry'])) {
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $doctor = $_POST['doctor'];
    $fee = $_POST['fee'];
    $date = date('Y-m-d');
    
    // 1. Generate PDF Filename
    $receipt_no = time();
    $filename = "Receipt_" . $receipt_no . ".pdf";
    $filepath = "../assets/receipts/" . $filename;
    $webpath = "https://aasthapadghanhospital.com/assets/receipts/" . $filename; // Update with your real domain
    
    // 2. Create PDF using FPDF
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(190,10,'Aastha Padghan Hospital',0,1,'C');
    $pdf->SetFont('Arial','',10);
    $pdf->Cell(190,5,'Padghan Surgical Hospital, Chikhli',0,1,'C');
    $pdf->Line(10, 30, 200, 30);
    $pdf->Ln(10);
    $pdf->SetFont('Arial','B',14);
    $pdf->Cell(190,10,'OPD RECEIPT',0,1,'C');
    $pdf->Ln(5);
    $pdf->SetFont('Arial','',12);
    $pdf->Cell(50,10,'Receipt No:',0,0); $pdf->Cell(100,10,$receipt_no,0,1);
    $pdf->Cell(50,10,'Date:',0,0); $pdf->Cell(100,10,$date,0,1);
    $pdf->Cell(50,10,'Patient Name:',0,0); $pdf->Cell(100,10,$name,0,1);
    $pdf->Cell(50,10,'Mobile:',0,0); $pdf->Cell(100,10,$phone,0,1);
    $pdf->Cell(50,10,'Doctor:',0,0); $pdf->Cell(100,10,$doctor,0,1);
    $pdf->Ln(10);
    $pdf->SetFillColor(230,230,230);
    $pdf->Cell(140,10,'Description',1,0,'C',true); $pdf->Cell(50,10,'Amount (INR)',1,1,'C',true);
    $pdf->Cell(140,10,'Consultation Fees',1,0); $pdf->Cell(50,10,$fee . '/-',1,1,'R');
    $pdf->SetFont('Arial','B',12);
    $pdf->Cell(140,10,'Total Paid',1,0,'R'); $pdf->Cell(50,10,$fee . '/-',1,1,'R');
    $pdf->Output('F', $filepath);

    // 3. Save to DB
    $stmt = $conn->prepare("INSERT INTO patient_entries (patient_name, phone, email, doctor, visit_date, consultation_fee, pdf_file) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssis", $name, $phone, $email, $doctor, $date, $fee, $filename);
    
    if ($stmt->execute()) {
        // 4. Send Email (Optional)
        if(!empty($email)) {
            $subject = "OPD Receipt - Aastha Hospital";
            $message = "Dear $name,\n\nHere is your receipt link:\n$webpath\n\n- Aastha Hospital";
            $headers = "From: no-reply@aasthapadghanhospital.com";
            mail($email, $subject, $message, $headers);
        }
        
        $msg = "Receipt Generated Successfully!";
        
        // 5. Create WhatsApp Link
        $wa_message = "Hello $name, here is your OPD Receipt from Aastha Hospital: $webpath";
        $wa_url = "https://wa.me/91$phone?text=" . urlencode($wa_message);
        
        $whatsapp_btn = '<a href="'.$wa_url.'" target="_blank" class="block w-full text-center bg-green-500 hover:bg-green-600 text-white font-bold py-3 rounded mt-3 shadow flex justify-center items-center gap-2 animate-pulse">
                            <img src="https://upload.wikimedia.org/wikipedia/commons/6/6b/WhatsApp.svg" class="w-6 h-6"> Send on WhatsApp
                         </a>';
    } else {
        $msg = "Error saving data.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Reception Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>body { font-family: 'Poppins', sans-serif; }</style>
</head>
<body class="bg-gray-100 min-h-screen">
    
    <nav class="bg-teal-800 text-white p-4 shadow-lg flex flex-wrap justify-between items-center sticky top-0 z-50">
        <div class="flex items-center gap-2 mb-2 md:mb-0">
            <span class="text-2xl bg-white rounded-full w-10 h-10 flex items-center justify-center shadow">🏥</span>
            <div>
                <h1 class="text-lg md:text-xl font-bold leading-tight">Reception Desk</h1>
                <p class="text-xs text-teal-200">Welcome, <?php echo $_SESSION['staff_user']; ?></p>
            </div>
        </div>
        
        <div class="flex flex-wrap gap-2 text-sm font-bold">
            <a href="upload_report.php" class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded shadow transition flex items-center gap-1">
                📂 Upload Report
            </a>
            <a href="beds.php" class="bg-orange-500 hover:bg-orange-600 text-white px-4 py-2 rounded shadow transition flex items-center gap-1">
                🛏️ Bed Manager
            </a>
            <a href="logout.php" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded shadow transition">
                Logout
            </a>
        </div>
    </nav>

    <div class="container mx-auto p-6 grid md:grid-cols-3 gap-6">
        
        <div class="md:col-span-1">
            <div class="bg-white p-6 rounded-lg shadow-md border-t-4 border-teal-500">
                <h2 class="text-xl font-bold mb-4 text-gray-800">New Patient Entry</h2>
                
                <?php if($msg) { ?>
                    <div class="bg-green-50 border border-green-200 text-green-800 p-4 rounded mb-6 text-sm">
                        <p class="font-bold">✅ <?php echo $msg; ?></p>
                        <?php if($whatsapp_btn) echo $whatsapp_btn; ?>
                    </div>
                <?php } ?>
                
                <form method="POST" class="space-y-4">
                    <div>
                        <label class="text-xs font-bold text-gray-500 uppercase tracking-wide">Patient Name</label>
                        <input type="text" name="name" required class="w-full border p-3 rounded focus:ring-2 focus:ring-teal-500 outline-none">
                    </div>
                    <div>
                        <label class="text-xs font-bold text-gray-500 uppercase tracking-wide">Phone Number</label>
                        <input type="number" name="phone" placeholder="Ex: 9922..." required class="w-full border p-3 rounded focus:ring-2 focus:ring-teal-500 outline-none">
                    </div>
                    <div>
                        <label class="text-xs font-bold text-gray-500 uppercase tracking-wide">Email (Optional)</label>
                        <input type="email" name="email" class="w-full border p-3 rounded focus:ring-2 focus:ring-teal-500 outline-none">
                    </div>
                    <div>
                        <label class="text-xs font-bold text-gray-500 uppercase tracking-wide">Assigned Doctor</label>
                        <select name="doctor" class="w-full border p-3 rounded bg-white focus:ring-2 focus:ring-teal-500 outline-none">
                            <option value="Dr. Gajanan Padghan">Dr. Gajanan Padghan</option>
                            <option value="Dr. Anita Padghan">Dr. Anita Padghan</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-xs font-bold text-gray-500 uppercase tracking-wide">Consultation Fee (₹)</label>
                        <input type="number" name="fee" value="200" class="w-full border p-3 rounded focus:ring-2 focus:ring-teal-500 outline-none">
                    </div>
                    <button type="submit" name="save_entry" class="w-full bg-teal-700 text-white font-bold py-3 rounded hover:bg-teal-800 transition shadow-lg mt-2 flex justify-center items-center gap-2">
                        <span>Generate Receipt</span>
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2.5 0a.5.5 0 01.5.5v3a.5.5 0 01-.5.5h-6a.5.5 0 01-.5-.5v-3a.5.5 0 01.5-.5h6z"></path></svg>
                    </button>
                </form>
            </div>
        </div>

        <div class="md:col-span-2">
            <div class="bg-white p-6 rounded-lg shadow-md h-full flex flex-col">
                
                <div class="flex justify-between items-center mb-4 pb-4 border-b">
                    <h2 class="text-xl font-bold text-gray-800">
                        Today's Entries 
                        <span class="text-xs font-normal text-gray-500 bg-gray-100 px-2 py-1 rounded ml-2 align-middle"><?php echo date('d M Y'); ?></span>
                    </h2>
                    <a href="history.php" class="bg-blue-600 hover:bg-blue-700 text-white text-sm px-4 py-2 rounded shadow transition flex items-center gap-2">
                        <span>📜 View History</span>
                    </a>
                </div>

                <div class="overflow-x-auto flex-grow">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="text-xs text-gray-500 border-b border-gray-200 bg-gray-50">
                                <th class="py-3 px-2">Receipt #</th>
                                <th class="py-3 px-2">Patient Name</th>
                                <th class="py-3 px-2">Doctor</th>
                                <th class="py-3 px-2">Fee</th>
                                <th class="py-3 px-2 text-right">Action</th>
                            </tr>
                        </thead>
                        <tbody class="text-sm">
                            <?php
                            $today = date('Y-m-d');
                            $res = $conn->query("SELECT * FROM patient_entries ORDER BY id DESC LIMIT 15");
                            if($res->num_rows > 0) {
                                while($row = $res->fetch_assoc()) {
                                    $rowDate = $row['visit_date'];
                                    $isToday = ($rowDate == $today);
                                    $dateLabel = $isToday ? '' : '<span class="text-[10px] text-gray-400 block">'.$rowDate.'</span>';
                                    $bgClass = $isToday ? 'bg-white' : 'bg-gray-50 opacity-80';

                                    // Generate WhatsApp Link for History Items too
                                    $hist_webpath = "https://aasthapadghanhospital.com/assets/receipts/" . $row['pdf_file'];
                                    $hist_msg = "Hello " . $row['patient_name'] . ", here is your Receipt: " . $hist_webpath;
                                    $hist_wa = "https://wa.me/91" . $row['phone'] . "?text=" . urlencode($hist_msg);

                                    echo '<tr class="border-b border-gray-100 hover:bg-teal-50 transition '.$bgClass.'">';
                                    echo '<td class="py-3 px-2 font-mono text-gray-500">#' . $row['id'] . '</td>';
                                    echo '<td class="py-3 px-2 font-bold text-gray-800">' . $row['patient_name'] . $dateLabel . '</td>';
                                    echo '<td class="py-3 px-2 text-teal-600 text-xs">' . $row['doctor'] . '</td>';
                                    echo '<td class="py-3 px-2 text-gray-600 font-bold">₹' . $row['consultation_fee'] . '</td>';
                                    echo '<td class="py-3 px-2 text-right flex justify-end gap-2">';
                                    // View PDF Button
                                    echo '<a href="../assets/receipts/' . $row['pdf_file'] . '" target="_blank" class="bg-red-100 text-red-600 px-2 py-1 rounded text-xs font-bold hover:bg-red-200 border border-red-200">PDF</a>';
                                    // Small WhatsApp Icon
                                    echo '<a href="'.$hist_wa.'" target="_blank" class="bg-green-100 text-green-600 px-2 py-1 rounded text-xs font-bold hover:bg-green-200 border border-green-200 flex items-center justify-center" title="Send on WhatsApp"><img src="https://upload.wikimedia.org/wikipedia/commons/6/6b/WhatsApp.svg" class="w-4 h-4"></a>';
                                    echo '</td>';
                                    echo '</tr>';
                                }
                            } else {
                                echo '<tr><td colspan="5" class="text-center py-8 text-gray-400 bg-gray-50 border-2 border-dashed border-gray-200 rounded-lg mt-2">No patient entries found yet.</td></tr>';
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

</body>
</html>