<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
include('includes/db.php');
include('includes/header.php');

// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];
/* ================= Auto Logout ================= */
$timeout_duration = 43200;

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
    header("Location: login.php?timeout=1");
    exit;
}
/* ================= HELPER ================= */
function calculate_age($dob) {
    if (!$dob || $dob === '0000-00-00') return '';
    try {
        $dobDate = new DateTime($dob);
        $now = new DateTime();
        $diff = $now->diff($dobDate);
        if ($diff->y >= 1) return $diff->y . ' Year' . ($diff->y > 1 ? 's' : '');
        if ($diff->m >= 1) return $diff->m . ' Month' . ($diff->m > 1 ? 's' : '');
        return $diff->d . ' Day' . ($diff->d > 1 ? 's' : '');
    } catch (Exception $e) {
        return '';
    }
}

function facility_abbr($facility_name) {
    $abbr = '';
    foreach (explode(' ', strtoupper($facility_name)) as $w) {
        if ($w !== '') $abbr .= $w[0];
    }
    return $abbr;
}

function generate_invoice_number($facility_name) {
    return facility_abbr($facility_name) . date('ymdHi') . mt_rand(1000, 9999);
}

function fetch_dropdown($pdo, $table, $facility_id, $status = 'enabled') {
    $stmt = $pdo->prepare("SELECT * FROM {$table} WHERE facility_id = ? AND status = ?");
    $stmt->execute([$facility_id, $status]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function fetch_patient($pdo, $patient_id) {
    $stmt = $pdo->prepare("SELECT * FROM patients WHERE id = ?");
    $stmt->execute([$patient_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function check_existing_department_visit($pdo, $patient_id, $department_id, $facility_id) {
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count 
        FROM visits 
        WHERE patient_id = ? 
          AND department_id = ? 
          AND facility_id = ?
          AND status = 'open'
    ");
    $stmt->execute([$patient_id, $department_id, $facility_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result['count'] > 0;
}

function fetch_facility_name($pdo, $facility_id) {
    $stmt = $pdo->prepare("SELECT name FROM facility WHERE id = ?");
    $stmt->execute([$facility_id]);
    return $stmt->fetchColumn() ?: 'FAC';
}

// ---------------- AUTH ----------------
if (!isset($_SESSION['user_id'], $_SESSION['facility_id'])) {
    $_SESSION['flash'] = [
        'message'=>'Session expired. Please login again.',
        'color'=>'#dc3545'
    ];
    header("Location: login.php");
    exit;
}
$session_facility_id = (int) $_SESSION['facility_id'];

// ---------------- Get Patient ----------------
$patient_id = (int) ($_GET['patient_id'] ?? 0);
if ($patient_id <= 0) {
    $_SESSION['flash'] = ['message'=>'Invalid patient ID','color'=>'#dc3545'];
    header("Location: patients.php");
    exit;
}
$patient = fetch_patient($pdo, $patient_id);
if (!$patient) {
    $_SESSION['flash'] = ['message'=>'Patient not found','color'=>'#dc3545'];
    header("Location: patients.php");
    exit;
}

// Facility isolation
$facility_id = (int) $patient['facility_id'];
if ($facility_id !== $session_facility_id) {
    $_SESSION['flash'] = [
        'message'=>'Unauthorized facility access',
        'color'=>'#dc3545'
    ];
    header("Location: dashboard.php");
    exit;
}

// ---------------- Dropdowns ----------------
$departments = fetch_dropdown($pdo, 'departments', $facility_id);
$insurances  = fetch_dropdown($pdo, 'insurance_partners', $facility_id);

// Check if patient has existing open visits and get their departments
$existing_visits_stmt = $pdo->prepare("
    SELECT v.department_id, d.name as department_name 
    FROM visits v
    JOIN departments d ON v.department_id = d.id
    WHERE v.patient_id = ? 
      AND v.facility_id = ?
      AND v.status = 'open'
");
$existing_visits_stmt->execute([$patient_id, $facility_id]);
$existing_open_visits = $existing_visits_stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Handle Form Submission ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_visit'])) {

    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['csrf_token']) {
        $_SESSION['flash'] = ['message'=>'Invalid CSRF token','color'=>'#dc3545'];
        header("Location: patients.php");
        exit;
    }

    // POST DATA
    $department_id             = (int) ($_POST['department_id'] ?? 0);
    $insurance_id              = (int) ($_POST['insurance_id'] ?? 0);
    $insurance_card_number     = trim($_POST['insurance_card_number'] ?? '');
    $visit_type                = $_POST['visit_type'] ?? '';
    $patient_co_pay_percentage = trim($_POST['patient_co_pay_percentage'] ?? '');
    $voucher_id                = trim($_POST['voucher_id'] ?? '');
    $affiliate_name            = trim($_POST['affiliate_name'] ?? '');
    $affiliate_affectation     = trim($_POST['affiliate_affectation'] ?? '');
    $beneficiary_relationship  = $_POST['beneficiary_relationship'] ?? '';
    $disease_type              = $_POST['disease_type'] ?? '';

    // Check for existing visit in same department
    if (check_existing_department_visit($pdo, $patient_id, $department_id, $facility_id)) {
        // Get department name for error message
        $stmt = $pdo->prepare("SELECT name FROM departments WHERE id = ?");
        $stmt->execute([$department_id]);
        $dept_name = $stmt->fetchColumn() ?: 'this department';
        
        $_SESSION['flash'] = [
            'message'=>'Patient already has an open visit in ' . $dept_name . '. Please select a different department.',
            'color'=>'#dc3545'
        ];
        header("Location: new_visit.php?patient_id=" . $patient_id);
        exit;
    }

    // Detect Private Insurance
    $is_private = false;
    if ($insurance_id) {
        $stmt = $pdo->prepare("SELECT name FROM insurance_partners WHERE id = ?");
        $stmt->execute([$insurance_id]);
        $insurance_name = strtolower($stmt->fetchColumn() ?? '');
        $is_private = str_contains($insurance_name, 'private');
    }

    // Validation
    $errors = [];
    if (!$department_id) $errors[] = "Department required";
    if (!$visit_type) $errors[] = "Visit type required";
    if ($patient_co_pay_percentage === '') $errors[] = "Co-pay required";
    if (!$disease_type) $errors[] = "Disease type required";

    if ($insurance_id && !$is_private) {
        if (!$insurance_card_number) $errors[] = "Insurance card required";
        if (!$affiliate_affectation) $errors[] = "Affiliate affectation required";
        if (!$beneficiary_relationship) $errors[] = "Relationship required";
    }

    if (!empty($errors)) {
        $_SESSION['flash'] = [
            'message'=>implode(', ', $errors),
            'color'=>'#dc3545'
        ];
        header("Location: new_visit.php?patient_id=".$patient_id);
        exit;
    }

    // Normalize for Private Insurance
    if ($is_private) {
        $insurance_card_number    = null;
        $voucher_id               = null;
        $affiliate_name           = null;
        $affiliate_affectation    = null;
        $beneficiary_relationship = null;
    }

    // CREATE VISIT - Removed preferred_doctor_id
    $stmt = $pdo->prepare("
        INSERT INTO visits (
            patient_id,
            facility_id,
            visit_date,
            department_id,
            insurance_id,
            insurance_card_number,
            visit_type,
            patient_co_pay_percentage,
            voucher_id,
            affiliate_name,
            affiliate_affectation,
            beneficiary_relationship,
            disease_type,
            created_by,
            status
        ) VALUES (?, ?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open')
    ");
    $stmt->execute([
        $patient_id,
        $facility_id,
        $department_id,
        $insurance_id,
        $insurance_card_number,
        $visit_type,
        $patient_co_pay_percentage,
        $voucher_id,
        $affiliate_name,
        $affiliate_affectation,
        $beneficiary_relationship,
        $disease_type,
        $_SESSION['user_id']
    ]);

    $visit_id = $pdo->lastInsertId();

    // VISIT TICKET
    $pdo->prepare("INSERT INTO visit_tickets (visit_id, patient_id, facility_id) VALUES (?, ?, ?)")
        ->execute([$visit_id, $patient_id, $facility_id]);

    // INVOICE
    $invoice_number = generate_invoice_number(fetch_facility_name($pdo, $facility_id));
    $pdo->prepare("INSERT INTO invoices (invoice_number, visit_id, patient_id, facility_id, amount, status) VALUES (?, ?, ?, ?, 0.00, 'unpaid')")
        ->execute([$invoice_number, $visit_id, $patient_id, $facility_id]);

    $_SESSION['flash'] = [
        'message'=>'Visit created successfully',
        'color'=>'#28a745'
    ];
    header("Location: all_visits.php");
    exit;
}

?>




<!-- ---------------- HTML ---------------- -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
  <?php include('includes/navbar.php'); ?>
</nav>
<div data-scroll-to-active="true" class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
  <?php include('includes/sidebar.php'); ?>
</div>
<div class="app-content content container-fluid">
  <div class="content-wrapper">
    <div class="col-xs-12">
      <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
          <h4 class="card-title">New Visit for <?= htmlspecialchars($patient['first_name'] . ' ' . ($patient['middle_name'] ?: '') . ' ' . $patient['last_name']) ?></h4>
        </div>
        <div class="card-body collapse in">
          <div class="card-block card-dashboard">

            <div class="mb-3">
              <strong>File ID:</strong> <?= htmlspecialchars($patient['file_id']) ?><br>
              <strong>Gender:</strong><?= htmlspecialchars($patient['gender']) ?><br>
              <strong>Age:</strong> <?= htmlspecialchars(calculate_age($patient['d_o_b'])) ?><br>
              <strong>Phone:</strong> <?= htmlspecialchars($patient['phone']) ?>
              
              <?php if (!empty($existing_open_visits)): ?>
                <div class="alert alert-warning mt-2">
                  <strong>Note:</strong> This patient already has open visit(s) in the following departments:
                  <ul class="mb-0 mt-1">
                    <?php foreach ($existing_open_visits as $visit): ?>
                      <li><?= htmlspecialchars($visit['department_name']) ?></li>
                    <?php endforeach; ?>
                  </ul>
                  <small class="text-muted">You can create a new visit only in a different department.</small>
                </div>
              <?php endif; ?>
            </div>

            <form method="post" id="visitForm">
              <input type="hidden" name="csrf" value="<?= $csrf ?>">

              <!-- Row 1: Basic Information -->
              <div class="row">
                <div class="col-md-4">
                  <label>Visit Date</label>
                  <?php $user_role = $_SESSION['user_role'] ?? '';  $can_edit_date = in_array($user_role, ['Super_admin','Admin','Doctor']); ?> 
                  <input type="date" name="visit_date" class="form-control" value="<?= date('Y-m-d') ?>" <?= $can_edit_date ? '' : 'disabled' ?>>
                </div>
                <div class="col-md-4">
                  <label>Department *</label>
                  <select name="department_id" class="form-control" required>
                    <option value="">-- Select Department --</option>
                    <?php foreach ($departments as $d): 
                      $is_disabled = false;
                      foreach ($existing_open_visits as $visit) {
                        if ($visit['department_id'] == $d['id']) {
                          $is_disabled = true;
                          break;
                        }
                      }
                    ?>
                      <option value="<?= $d['id'] ?>" <?= $is_disabled ? 'disabled' : '' ?>>
                        <?= htmlspecialchars($d['name']) ?>
                        <?= $is_disabled ? ' (Already has open visit)' : '' ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                  <?php if (!empty($existing_open_visits)): ?>
                    <small class="text-muted">Disabled departments already have open visits</small>
                  <?php endif; ?>
                </div>
                <div class="col-md-4">
                  <label>Insurance *</label>
                  <select name="insurance_id" id="insuranceSelect" class="form-control" required>
                    <option value="">-- Select Insurance --</option>
                    <?php foreach($insurances as $ins): ?>
                      <option value="<?= $ins['id'] ?>"><?= htmlspecialchars($ins['name']) ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>

              <!-- Row 2: Insurance Details (Non-Private) -->
              <div class="row mt-2">
                <div class="col-md-4 nonPrivateField">
                  <label>Insurance Card Number *</label>
                  <input type="text" name="insurance_card_number" class="form-control">
                </div>
                <div class="col-md-4 nonPrivateField">
                  <label>Affiliate's Name (Optional)</label>
                  <input type="text" name="affiliate_name" class="form-control">
                </div>
                <div class="col-md-4 nonPrivateField">
                  <label>Affiliate's Affectation *</label>
                  <input type="text" name="affiliate_affectation" class="form-control">
                </div>
              </div>

              <!-- Row 3: Remaining fields without gap -->
              <div class="row mt-2">
                <div class="col-md-4 nonPrivateField">
                  <label>Beneficiary Relationship *</label>
                  <select name="beneficiary_relationship" class="form-control">
                    <option value="">-- Select --</option>
                    <option value="Self">Self</option>
                    <option value="Spouse">Spouse</option>
                    <option value="Child">Child</option>
                    <option value="Other">Other</option>
                  </select>
                </div>
                <div class="col-md-4" id="voucherBox">
                  <label>Voucher Identification</label>
                  <input type="text" name="voucher_id" class="form-control">
                </div>
                <div class="col-md-4">
                  <label>Disease Type *</label>
                  <select name="disease_type" id="disease_type" class="form-control" required>
                    <option value="">-- Select --</option>
                    <option value="Natural Disease">Natural Disease</option>
                    <option value="Occupation Disease">Occupation Disease</option>
                    <option value="Work-Related Disease">Work-Related Disease</option>
                    <option value="Road Traffic Accident">Road Traffic Accident</option>
                    <option value="Other">Other</option>
                  </select>
                </div>
              </div>

              <!-- Row 4: Final row -->
              <div class="row mt-2">
                <div class="col-md-4">
                  <label>Patient Visit Type *</label>
                  <select name="visit_type" id="patientCoPaySelect" class="form-control" required>
                    <option value="">-- Select --</option>
                    <option value="In">In</option>
                    <option value="Out">Out</option>
                  </select>
                </div>
                <div class="col-md-4">
                  <label>Co-Pay Amount *</label>
                  <input type="text" name="patient_co_pay_percentage" id="coPayAmountInput" class="form-control" required>
                </div>
              </div>

              <div class="mt-3">
                <button type="submit" name="create_visit" class="btn btn-outline-primary btn-md">Save Visit</button>
                <a href="all_patients.php" class="btn btn-outline-secondary btn-md">Cancel</a>
              </div>
            </form>

          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<style>
.toast-message {
    position: fixed;
    top: 20px;
    right: 20px;
    min-width: 280px;
    max-width: 420px;
    padding: 14px 18px;
    border-radius: 6px;
    color: #fff;
    font-size: 14px;
    font-weight: 500;
    z-index: 99999;
    box-shadow: 0 6px 20px rgba(0,0,0,0.25);
    animation: slideInRight 0.4s ease, fadeOut 0.4s ease 3.6s;
}

.invalid-field {
    border-color: #dc3545 !important;
    box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25) !important;
}

@keyframes slideInRight {
    from {
        opacity: 0;
        transform: translateX(100%);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

@keyframes fadeOut {
    to {
        opacity: 0;
        transform: translateX(20%);
    }
}
</style>

<!-- ---------------- JS ---------------- -->
<script>
// Toggle Non-private & Voucher Fields
function toggleInsuredFields() {
    const insuranceSelect = document.getElementById('insuranceSelect');
    const selectedText = insuranceSelect.options[insuranceSelect.selectedIndex]?.text.toLowerCase() || '';
    const nonPrivateFields = document.querySelectorAll('.nonPrivateField');
    const voucherBox = document.getElementById('voucherBox');

    if(selectedText.includes('private')) {
        nonPrivateFields.forEach(f => {
            f.style.display='none';
            f.querySelectorAll('input, select').forEach(i => i.required = false);
        });
        voucherBox.style.display='none';
    } else {
        nonPrivateFields.forEach(f => {
            f.style.display='block';
            f.querySelectorAll('input, select').forEach(i => i.required = true);
        });
        voucherBox.style.display='block';
    }
}
document.getElementById('insuranceSelect').addEventListener('change', toggleInsuredFields);

// Form Validation
document.getElementById('visitForm').addEventListener('submit', function(e){
    let errors = [];
    const form = e.target;

    document.querySelectorAll('.invalid-field')
        .forEach(f=>f.classList.remove('invalid-field'));

    const requiredFields = [
        {el: form.department_id, msg:"Department required"},
        {el: form.visit_type, msg:"Patient Visit Type required"},
        {el: form.patient_co_pay_percentage, msg:"Co-Pay Amount required"},
        {el: form.disease_type, msg:"Disease Type required"}
    ];

    requiredFields.forEach(f=>{
        if(!f.el.value){
            errors.push(f.msg);
            f.el.classList.add('invalid-field');
        }
    });

    const insuranceSelect = form.insurance_id;
    const selectedText = insuranceSelect.options[insuranceSelect.selectedIndex]?.text.toLowerCase() || '';

    if(selectedText && !selectedText.includes('private')) {
        const nonPrivateFields = [
            {el: form.insurance_card_number, msg:"Insurance Card Number required"},
            {el: form.affiliate_affectation, msg:"Affiliate Affectation required"},
            {el: form.beneficiary_relationship, msg:"Beneficiary Relationship required"}
        ];
        nonPrivateFields.forEach(f=>{
            if(!f.el.value){
                errors.push(f.msg);
                f.el.classList.add('invalid-field');
            }
        });
    }

    if(errors.length){
        e.preventDefault();
        showToast(errors.join(", "), '#dc3545');
    }
});

// Toast Message
function showToast(message, color='#dc3545'){
    const toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.style.background = color;
    toast.innerText = message;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
}

// Initialize on load
window.onload=function(){
    toggleInsuredFields();
};

// Server Flash
<?php if(isset($_SESSION['flash'])): ?>
showToast(
    <?= json_encode($_SESSION['flash']['message']) ?>,
    <?= json_encode($_SESSION['flash']['color']) ?>
);
<?php unset($_SESSION['flash']); endif; ?>
</script>

<?php include('includes/footer.php'); ?>