<?php
/**
 * List All Cases
 * Paginated list of all cases with search and filters
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];

$page = (int)($_GET['page'] ?? 1);
$status = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query
$where = "user_id = ?";
$params = [$userId];

if ($status != 'all') {
    $where .= " AND status = ?";
    $params[] = $status;
}
if (!empty($search)) {
    $where .= " AND (patient_name LIKE ? OR patient_mobile LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

// Get total count
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM cases WHERE $where");
$stmt->execute($params);
$totalCases = $stmt->fetch()['total'];
$totalPages = ceil($totalCases / $limit);

// Get cases
$sql = "SELECT c.*, r.name as remedy_name 
        FROM cases c
        LEFT JOIN remedies r ON c.prescribed_remedy_id = r.id
        WHERE $where
        ORDER BY c.created_at DESC
        LIMIT $limit OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$cases = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Cases</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <style>
        .sidebar { min-height: 100vh; background: linear-gradient(135deg, #1a472a 0%, #0d2818 100%); position: fixed; left: 0; top: 0; width: 260px; }
        .sidebar .nav-link { color: rgba(255,255,255,0.8); padding: 12px 20px; margin: 5px 10px; border-radius: 8px; transition: all 0.3s; }
        .sidebar .nav-link:hover { background: rgba(255,255,255,0.1); transform: translateX(5px); }
        .sidebar .nav-link.active { background: #2ecc71; color: white; }
        .sidebar .nav-link i { margin-right: 10px; width: 20px; }
        .main-content { margin-left: 260px; padding: 20px; }
        .top-navbar { background: white; border-radius: 12px; padding: 15px 25px; margin-bottom: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        @media (max-width: 768px) { .sidebar { width: 70px; } .sidebar .nav-link span { display: none; } .main-content { margin-left: 70px; } }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="text-center py-4"><h4 class="text-white mb-0">🏥 Homoeopathy</h4></div>
        <nav class="nav flex-column mt-3">
            <a class="nav-link" href="../dashboard.php"><i class="fas fa-tachometer-alt"></i> <span>Dashboard</span></a>
            <a class="nav-link" href="index.php"><i class="fas fa-folder-open"></i> <span>Cases</span></a>
            <a class="nav-link active" href="list.php"><i class="fas fa-list"></i> <span>All Cases</span></a>
            <a class="nav-link" href="new.php"><i class="fas fa-plus-circle"></i> <span>New Case</span></a>
            <a class="nav-link" href="../repertory/index.php"><i class="fas fa-book"></i> <span>Repertory</span></a>
            <a class="nav-link" href="../profile.php"><i class="fas fa-user"></i> <span>Profile</span></a>
            <hr><a class="nav-link" href="../../logout.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
        </nav>
    </div>
    
    <div class="main-content">
        <div class="top-navbar">
            <div class="d-flex justify-content-between"><h4 class="mb-0"><i class="fas fa-list"></i> My Cases</h4><a href="new.php" class="btn btn-primary"><i class="fas fa-plus"></i> New Case</a></div>
        </div>
        
        <!-- Filters -->
        <div class="card mb-4"><div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-3"><input type="text" name="search" class="form-control" placeholder="Search patient..." value="<?php echo escape($search); ?>"></div>
                <div class="col-md-2"><select name="status" class="form-control"><option value="all" <?php echo $status=='all'?'selected':''; ?>>All Status</option><option value="active" <?php echo $status=='active'?'selected':''; ?>>Active</option><option value="follow-up" <?php echo $status=='follow-up'?'selected':''; ?>>Follow-up</option><option value="closed" <?php echo $status=='closed'?'selected':''; ?>>Closed</option></select></div>
                <div class="col-md-2"><button type="submit" class="btn btn-primary">Filter</button><a href="list.php" class="btn btn-secondary ms-2">Reset</a></div>
                <div class="col-md-5 text-end"><a href="export.php?<?php echo http_build_query($_GET); ?>" class="btn btn-success"><i class="fas fa-download"></i> Export</a><a href="import.php" class="btn btn-info ms-2"><i class="fas fa-upload"></i> Import</a></div>
            </form>
        </div></div>
        
        <!-- Cases Table -->
        <div class="card"><div class="card-body">
            <div class="table-responsive"><table class="table table-bordered table-hover" id="casesTable">
                <thead><tr><th>ID</th><th>Date</th><th>Patient Name</th><th>Mobile</th><th>Prescribed Remedy</th><th>Status</th><th>Follow-up Date</th><th>Actions</th></tr></thead>
                <tbody>
                    <?php foreach($cases as $case): ?>
                    <tr>
                        <td><?php echo $case['id']; ?></td>
                        <td><?php echo date('d-m-Y', strtotime($case['created_at'])); ?></td>
                        <td><strong><?php echo escape($case['patient_name']); ?></strong></td>
                        <td><?php echo $case['patient_mobile']; ?></td>
                        <td><?php echo $case['remedy_name'] ?? '<span class="text-muted">Not prescribed</span>'; ?></td>
                        <td><span class="badge bg-<?php echo $case['status']=='active'?'success':($case['status']=='follow-up'?'warning':'secondary'); ?>"><?php echo ucfirst($case['status']); ?></span></td>
                        <td><?php echo $case['follow_up_date'] ? date('d-m-Y', strtotime($case['follow_up_date'])) : '-'; ?></td>
                        <td><a href="view.php?id=<?php echo $case['id']; ?>" class="btn btn-sm btn-info">View</a><a href="edit.php?id=<?php echo $case['id']; ?>" class="btn btn-sm btn-primary ms-1">Edit</a><a href="prescribe.php?id=<?php echo $case['id']; ?>" class="btn btn-sm btn-success ms-1">Rx</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table></div>
            <?php echo pagination($page, $totalPages, 'list.php?' . http_build_query(array_merge($_GET, ['page' => 'PAGE']))); ?>
        </div></div>
    </div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script>$(document).ready(function() { $('#casesTable').DataTable({ paging: false, searching: false }); });</script>
</body>
</html>