<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

/* ================= Session Timeout (12 hours) ================= */
$SESSION_TIMEOUT = 43200;

if (isset($_SESSION['LAST_ACTIVITY'])) {
    if (time() - $_SESSION['LAST_ACTIVITY'] > $SESSION_TIMEOUT) {
        session_unset();
        session_destroy();
        header("Location: login.php?timeout=1");
        exit;
    }
}
$_SESSION['LAST_ACTIVITY'] = time();

include('includes/db.php');
include('includes/header.php');


/* ================= AUTO LOGOUT ================= */
$timeout_duration = 1800;
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
    header("Location: login.php?timeout=1");
    exit;
}
$_SESSION['LAST_ACTIVITY'] = time();

/* ================= AUTH ================= */
if (empty($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

/* ================= CSRF ================= */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

/* ================= FACILITY LOCK ================= */
if (empty($_SESSION['facility_id'])) {
    $_SESSION['flash'] = [
        'message' => 'No facility assigned to your account.',
        'color'   => '#dc3545'
    ];
    header("Location: login.php");
    exit;
}

$facility_id = (int)$_SESSION['facility_id'];
$user_id     = (int)$_SESSION['user_id'];
$user_role   = $_SESSION['user_role'] ?? '';

/* ================= 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 getViewLink($role, $visit, $pdo, $facility_id) {
    // Receptionist and Cashier go to invoices
    if (in_array($role, ['Receptionist', 'Cashier'])) {
        return "invoices.php?visit_id={$visit['id']}&patient_id={$visit['patient_id']}";
    }
    
    // Nurse sees all visits - goes to visit ticket
    if ($role === 'Nurse') {
        return "visit_ticket.php?id={$visit['id']}";
    }
    
    // For Doctors, Dentist and other department staff: redirect to their associated department visits
    // Only show visits from their own department
    $department_roles = ['Doctor', 'Dentist', 'Lab Technician', 'Radiology Technician', 'Pharmacy Technician'];
    if (in_array($role, $department_roles)) {
        // Get user's department
        $stmt = $pdo->prepare("SELECT department_id FROM users WHERE id = ? AND facility_id = ?");
        $stmt->execute([$_SESSION['user_id'], $facility_id]);
        $user_dept = $stmt->fetchColumn();
        
        // If user has no department or visit is not in their department, show nothing or redirect differently
        if (!$user_dept || $visit['department_id'] != $user_dept) {
            // Return a special link - they shouldn't see this visit
            return "#";
        }
        
        // If visit is in their department, go to visit ticket
        return "visit_ticket.php?id={$visit['id']}";
    }
    
    // Default for Super_admin, Admin, etc.
    return "visit_ticket.php?id={$visit['id']}";
}

/* ================= FILTER INPUT ================= */
$from_date = $_GET['from_date'] ?? '';
$to_date   = $_GET['to_date'] ?? '';
$view_all  = isset($_GET['view_all']);

/* ================= Handle Discharge Patient Action ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['discharge_patient'])) {
    if ($_POST['csrf'] !== $_SESSION['csrf_token']) {
        $_SESSION['flash'] = ['message' => 'Invalid CSRF token', 'color' => '#dc3545'];
        header("Location: all_visits.php");
        exit;
    }
    
    // Check if user has permission to discharge
    $allowed_roles = ['Doctor', 'Dentist', 'Admin', 'Super_admin'];
    if (!in_array($user_role, $allowed_roles)) {
        $_SESSION['flash'] = ['message' => 'You do not have permission to discharge patients', 'color' => '#dc3545'];
        header("Location: all_visits.php");
        exit;
    }
    
    $visit_id = (int)($_POST['discharge_visit_id'] ?? 0);
    if (!$visit_id) {
        $_SESSION['flash'] = ['message' => 'Invalid Visit ID', 'color' => '#dc3545'];
        header("Location: all_visits.php");
        exit;
    }
    
    // Check if visit exists and belongs to facility
    $stmt = $pdo->prepare("SELECT id, discharge_time FROM visits WHERE id = ? AND facility_id = ?");
    $stmt->execute([$visit_id, $facility_id]);
    $visit_check = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$visit_check) {
        $_SESSION['flash'] = ['message' => 'Visit not found', 'color' => '#dc3545'];
        header("Location: all_visits.php");
        exit;
    }
    
    // Check if already discharged
    if (!empty($visit_check['discharge_time'])) {
        $_SESSION['flash'] = ['message' => 'Patient is already discharged', 'color' => '#dc3545'];
        header("Location: all_visits.php");
        exit;
    }
    
    try {
        // Begin transaction
        $pdo->beginTransaction();
        
        // Set discharge time only - keep visit status as 'open'
        $current_time = date('Y-m-d H:i:s');
        $stmt = $pdo->prepare("
            UPDATE visits SET 
                discharge_time = ?
            WHERE id = ? AND facility_id = ?
        ");
        $stmt->execute([
            $current_time, 
            $visit_id,
            $facility_id
        ]);
        
        // Commit transaction
        $pdo->commit();
        
        $_SESSION['flash'] = ['success' => true, 'message' => 'Patient discharged successfully. Treatment completed.', 'color' => '#28a745'];
        header("Location: all_visits.php");
        exit;
        
    } catch (PDOException $e) {
        // Rollback on error
        $pdo->rollBack();
        $_SESSION['flash'] = ['success' => false, 'message' => 'Error discharging patient: ' . $e->getMessage(), 'color' => '#dc3545'];
        header("Location: all_visits.php");
        exit;
    }
}

/* ================= CLOSE VISIT - REMOVED ================= */
/* ================= REOPEN VISIT - REMOVED ================= */

/* ================= FETCH VISITS WITH ROLE FILTERS ================= */
$where  = ['v.facility_id = ?'];
$params = [$facility_id];

// Apply role-based filters
$department_roles = ['Doctor', 'Dentist', 'Lab Technician', 'Radiology Technician', 'Pharmacy Technician'];
if (in_array($user_role, $department_roles)) {
    // Get user's department
    $stmt = $pdo->prepare("SELECT department_id FROM users WHERE id = ? AND facility_id = ?");
    $stmt->execute([$user_id, $facility_id]);
    $user_dept = $stmt->fetchColumn();
    
    if ($user_dept) {
        $where[] = 'v.department_id = ?';
        $params[] = $user_dept;
    }
}

// Date filters
if (!$view_all && !$from_date && !$to_date) {
    $where[] = 'DATE(v.visit_date) = CURDATE()';
}
if ($from_date && $to_date) {
    $where[]  = 'DATE(v.visit_date) BETWEEN ? AND ?';
    $params[] = $from_date;
    $params[] = $to_date;
}

$whereSQL = 'WHERE ' . implode(' AND ', $where);

$stmt = $pdo->prepare("
    SELECT v.*,
           p.id AS patient_id,
           p.first_name, p.middle_name, p.last_name,
           p.file_id, p.d_o_b, p.gender,
           d.name AS department_name,
           u.username AS doctor_name,
           i.name AS insurance_name
    FROM visits v
    JOIN patients p 
         ON p.id = v.patient_id AND p.facility_id = ?
    LEFT JOIN departments d ON d.id = v.department_id
    LEFT JOIN users u ON u.id = v.treated_by
    LEFT JOIN insurance_partners i ON i.id = v.insurance_id
    $whereSQL
    ORDER BY v.created_at DESC
");
$stmt->execute(array_merge([$facility_id], $params));
$visits = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!-- ================== HTML ================== -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
  <?php include('includes/navbar.php'); ?>
</nav>

<div 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">Daily Visits</h4>
    <a href="all_patients.php" class="btn btn-outline-primary btn-lg">All Patients</a>
</div>

<div class="card-body collapse in">
<div class="card-block card-dashboard">

<!-- ================= FILTER BAR ================= -->
<form method="get" class="row mb-2">
    <div class="col-md-3">
        <input type="date" name="from_date" value="<?= htmlspecialchars($from_date) ?>" class="form-control">
    </div>
    <div class="col-md-3">
        <input type="date" name="to_date" value="<?= htmlspecialchars($to_date) ?>" class="form-control">
    </div>
    <div class="col-md-6">
        <button class="btn btn-primary">Filter</button>
        <a href="all_visits.php?view_all=1" class="btn btn-success">View All</a>
        <a href="all_visits.php" class="btn btn-outline-danger">Reset</a>
    </div>
</form>

<div class="table-responsive">
<table class="table table-hover mb-0" id="Table">
<thead>
<tr>
    <th>File ID</th>
    <th>Patient Names</th>
    <th>Age & Gender</th>
    <th>Visit Date</th>
    <th>Treated by</th>
    <th>Department</th>
    <th>Insurance</th>
    <th>Status</th>
</tr>
</thead>
<tbody>
<?php foreach($visits as $v): 
    $view_link = getViewLink($user_role, $v, $pdo, $facility_id);
?>
<tr>
<td>
    <div><?= htmlspecialchars($v['file_id']) ?></div>
    <div>
        <!-- View and Edit Links - only show if user has access -->
        <?php if ($view_link !== '#'): ?>
            <a href="<?= $view_link ?>" class="btn btn-sm btn-outline-info">View</a>
        <?php endif; ?>
        
        <!-- Edit link - only for certain roles -->
        <?php if (in_array($user_role, ['Receptionist', 'Super_admin', 'Admin'])): ?>
            <a href="edit_visit.php?visit_id=<?= $v['id'] ?>" class="btn btn-sm btn-outline-primary">Edit</a>
        <?php endif; ?>
    </div>
</td>

<td><?= htmlspecialchars($v['first_name'].' '.$v['middle_name'].' '.$v['last_name']) ?></td>
<td>
    <div><?= htmlspecialchars($v['gender']) ?></div>
    <div><?= calculate_age($v['d_o_b']) ?></div>
</td>
<td><?= date("Y-m-d H:i:s", strtotime($v['visit_date'])) ?></td>
<td><?= htmlspecialchars($v['doctor_name'] ?: '-') ?></td>
<td><?= htmlspecialchars($v['department_name'] ?: '-') ?></td>
<td><?= htmlspecialchars($v['insurance_name'] ?: '-') ?></td>
<td>
    <!-- Status with Discharge Button -->
    <?php if (empty($v['discharge_time'])): ?>
        <!-- Not Discharged - Show "On going" button that can trigger discharge -->
        <?php if (in_array($user_role, ['Doctor', 'Dentist', 'Admin', 'Super_admin'])): ?>
            <form method="post" style="display:inline-block;">
                <input type="hidden" name="csrf" value="<?= $csrf ?>">
                <input type="hidden" name="discharge_visit_id" value="<?= $v['id'] ?>">
                <button type="submit" 
                        name="discharge_patient" 
                        class="btn btn-sm btn-success"
                        onclick="return confirm('Are you sure you want to discharge this patient? This will mark treatment as completed.')">
                    On going
                </button>
            </form>
        <?php else: ?>
            <span class="btn btn-sm btn-success">On going</span>
        <?php endif; ?>
    <?php else: ?>
        <!-- Already Discharged -->
        <span class="btn btn-sm btn-warning " style="color: black">Discharged</span>
        <small class=" d-block">
            <?= date("M d, H:i", strtotime($v['discharge_time'])) ?>
        </small>
    <?php endif; ?>
    
    <!-- Visit Status -->
    <?php if ($v['status'] === 'open'): ?>
        <div><span class="badge badge-success"></span></div>
    <?php else: ?>
        <div><span class="badge badge-danger"></span></div>
    <?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

<!-- ================= CUSTOM TOAST ================= -->
<div id="toastContainer" style="position:fixed; top:20px; right:20px; z-index:9999;"></div>
<?php include('includes/footer.php'); ?>

<style>
.toast-message {
    display: flex; align-items: center;
    padding: 12px 20px; margin-bottom: 10px;
    color: #fff; border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    font-size: 14px; opacity: 0; transform: translateX(100%);
    transition: all 0.5s ease;
}
.toast-message.show { opacity: 1; transform: translateX(0); }
.toast-message .close-btn { margin-left: 10px; cursor: pointer; font-weight: bold; }
</style>

<script>
function showToast(message, bgColor='#333') {
    let container = document.getElementById('toastContainer');
    let toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.style.background = bgColor;
    toast.innerHTML = message + '<span class="close-btn" onclick="this.parentElement.remove()">×</span>';
    container.appendChild(toast);
    setTimeout(()=>{ toast.classList.add('show'); }, 100);
    setTimeout(()=>{ toast.classList.remove('show'); setTimeout(()=>toast.remove(),500); }, 5000);
}
<?php if(isset($_SESSION['flash'])): ?>
showToast("<?= addslashes($_SESSION['flash']['message']) ?>", "<?= $_SESSION['flash']['color'] ?>");
<?php unset($_SESSION['flash']); endif; ?>

setInterval(function(){
    document.querySelectorAll('.countdown').forEach(function(el){
        let t = parseInt(el.dataset.time)*1000 - Date.now();
        if (t <= 0) { el.innerText = 'Time over'; return; }
        let m = Math.floor(t/60000); let s = Math.floor((t%60000)/1000);
        el.innerText = `Closing in ${m}m ${s}s`;
    });
}, 1000);
</script>