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

if (!isset($_SESSION['doctor'])) {
    header('Location: login.php');
    exit;
}

$doctor_id = $_SESSION['doctor'];
$msg = '';
$appt_id = (int)($_GET['appt_id'] ?? 0);

// Get appointment
$appt = $conn->query("SELECT a.*, p.name AS patient_name, p.mobile, p.id AS patient_id 
    FROM opd_appointments a JOIN opd_patients p ON a.patient_id = p.id 
    WHERE a.id = $appt_id AND a.doctor_id = $doctor_id")->fetch_assoc();

if (!$appt) {
    echo "<div style='padding:20px;font-family:sans-serif;'><h3>❌ অ্যাপয়েন্টমেন্ট পাওয়া যায়নি</h3>
    <p>Appointment ID: $appt_id | Doctor ID: $doctor_id</p>
    <a href='dashboard.php'>← ড্যাশবোর্ডে ফিরুন</a></div>";
    exit;
}

// Handle bill
if (isset($_POST['generate_bill'])) {
    $amount = (float)$_POST['amount'];
    $desc = $conn->real_escape_string($_POST['description']);
    $sql = "INSERT INTO opd_bills (appointment_id, patient_id, amount, description) 
            VALUES ($appt_id, {$appt['patient_id']}, $amount, '$desc')";
    if ($conn->query($sql)) {
        $msg = '<div class="alert alert-success">✅ বিল তৈরি হয়েছে!</div>';
    } else {
        $msg = '<div class="alert alert-danger">❌ Error: '.$conn->error.'</div>';
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8"><title>Billing</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4">
<div class="container" style="max-width:600px">
    <a href="dashboard.php" class="btn btn-secondary mb-3">← ফিরুন</a>
    <?=$msg?>
    <div class="card">
        <div class="card-header bg-success text-white"><h5>💰 বিল তৈরি - <?=$appt['patient_name']?></h5></div>
        <div class="card-body">
            <p><strong>সিরিয়াল:</strong> #<?=$appt['serial_no']?></p>
            <p><strong>তারিখ:</strong> <?=date('d/m/Y', strtotime($appt['appointment_date']))?></p>
            <form method="POST">
                <input type="number" name="amount" class="form-control mb-2" value="500" required>
                <input type="text" name="description" class="form-control mb-3" value="Consultation Fee">
                <button type="submit" name="generate_bill" class="btn btn-success w-100">Generate Bill</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>