<?php
/**
 * Manage Doctors - List View
 * Display all doctors with search, filter, and pagination
 */

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

// Check if user is logged in and is admin
requireAdmin();

$pdo = getDB();
$message = '';
$error = '';

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['bulk_action'])) {
    $selectedIds = $_POST['selected_ids'] ?? [];
    $bulkAction = $_POST['bulk_action'];
    
    if (!empty($selectedIds)) {
        $placeholders = implode(',', array_fill(0, count($selectedIds), '?'));
        
        if ($bulkAction == 'activate') {
            $stmt = $pdo->prepare("UPDATE users SET is_active = 1 WHERE id IN ($placeholders) AND role = 'doctor'");
            $stmt->execute($selectedIds);
            $message = count($selectedIds) . " doctors activated.";
        } elseif ($bulkAction == 'deactivate') {
            $stmt = $pdo->prepare("UPDATE users SET is_active = 0 WHERE id IN ($placeholders) AND role = 'doctor'");
            $stmt->execute($selectedIds);
            $message = count($selectedIds) . " doctors deactivated.";
        } elseif ($bulkAction == 'delete') {
            // Check if any doctor has cases
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM cases WHERE user_id IN ($placeholders)");
            $stmt->execute($selectedIds);
            $caseCount = $stmt->fetch()['count'];
            
            if ($caseCount > 0) {
                $error = "Cannot delete doctors with existing cases. Delete or reassign cases first.";
            } else {
                $stmt = $pdo->prepare("DELETE FROM users WHERE id IN ($placeholders) AND role = 'doctor'");
                $stmt->execute($selectedIds);
                $message = count($selectedIds) . " doctors deleted.";
            }
        }
    }
}

// Get filter parameters
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? 'all';
$plan = $_GET['plan'] ?? 'all';
$page = (int)($_GET['page'] ?? 1);
$limit = ITEMS_PER_PAGE;
$offset = ($page - 1) * $limit;

// Build query
$whereConditions = ["u.role = 'doctor'"];
$params = [];

if (!empty($search)) {
    $whereConditions[] = "(u.full_name LIKE ? OR u.email LIKE ? OR u.username LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if ($status == 'active') {
    $whereConditions[] = "u.is_active = 1";
} elseif ($status == 'inactive') {
    $whereConditions[] = "u.is_active = 0";
}

if ($plan != 'all') {
    $whereConditions[] = "s.plan_type = ?";
    $params[] = $plan;
}

$whereClause = implode(" AND ", $whereConditions);

// Get total count for pagination
$countSql = "SELECT COUNT(DISTINCT u.id) as total 
             FROM users u 
             LEFT JOIN subscriptions s ON u.id = s.user_id AND s.is_active = 1
             WHERE $whereClause";
$stmt = $pdo->prepare($countSql);
$stmt->execute($params);
$totalDoctors = $stmt->fetch()['total'];
$totalPages = ceil($totalDoctors / $limit);

// Get doctors list
$sql = "SELECT u.*, 
        s.plan_type, s.start_date, s.end_date, s.amount,
        (SELECT COUNT(*) FROM cases WHERE user_id = u.id) as total_cases,
        (SELECT COUNT(*) FROM cases WHERE user_id = u.id AND status = 'active') as active_cases,
        DATEDIFF(s.end_date, CURDATE()) as days_remaining
        FROM users u 
        LEFT JOIN subscriptions s ON u.id = s.user_id AND s.is_active = 1
        WHERE $whereClause
        ORDER BY u.created_at DESC
        LIMIT ? OFFSET ?";

$params[] = $limit;
$params[] = $offset;
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$doctors = $stmt->fetchAll();

// Get subscription plans for filter
$stmt = $pdo->query("SELECT DISTINCT plan_type FROM subscriptions");
$plans = $stmt->fetchAll();

// Get statistics
$stmt = $pdo->query("SELECT 
                    COUNT(*) as total,
                    SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active,
                    SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as inactive
                    FROM users WHERE role = 'doctor'");
$stats = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Doctors - Admin Panel</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: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: #34495e;
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #3498db;
        }
        .sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .top-navbar {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 15px 20px;
        }
        .status-badge {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
        }
        .status-active { background: #d4edda; color: #155724; }
        .status-inactive { background: #f8d7da; color: #721c24; }
        .filter-section {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .stats-card {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .stats-number {
            font-size: 28px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin Panel</h4>
                    <small class="text-muted"><?php echo APP_VERSION; ?></small>
                </div>
                <nav class="nav flex-column">
                    <a class="nav-link" href="../dashboard.php">
                        <i class="fas fa-tachometer-alt"></i> Dashboard
                    </a>
                    <a class="nav-link active" href="index.php">
                        <i class="fas fa-user-md"></i> Doctors
                    </a>
                    <a class="nav-link" href="../subscriptions/index.php">
                        <i class="fas fa-credit-card"></i> Subscriptions
                    </a>
                    <a class="nav-link" href="../rubrics/index.php">
                        <i class="fas fa-tree"></i> Rubrics
                    </a>
                    <a class="nav-link" href="../remedies/index.php">
                        <i class="fas fa-capsules"></i> Remedies
                    </a>
                    <a class="nav-link" href="../reports/index.php">
                        <i class="fas fa-chart-line"></i> Reports
                    </a>
                    <a class="nav-link" href="../settings/index.php">
                        <i class="fas fa-cog"></i> Settings
                    </a>
                    <a class="nav-link" href="../profile.php">
                        <i class="fas fa-user"></i> My Profile
                    </a>
                    <hr class="bg-secondary">
                    <a class="nav-link" href="../../logout.php">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </nav>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <div class="d-flex justify-content-between align-items-center">
                        <h4 class="mb-0"><i class="fas fa-user-md"></i> Manage Doctors</h4>
                        <div>
                            <span class="me-3">
                                <i class="fas fa-user-circle"></i> 
                                <?php echo escape($_SESSION['full_name']); ?>
                            </span>
                            <span class="badge bg-primary">Admin</span>
                        </div>
                    </div>
                </div>
                
                <div class="p-4">
                    <!-- Alert Messages -->
                    <?php if ($message): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <i class="fas fa-check-circle"></i> <?php echo $message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo $stats['total']; ?></div>
                                <div class="text-muted">Total Doctors</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number text-success"><?php echo $stats['active']; ?></div>
                                <div class="text-muted">Active Doctors</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number text-danger"><?php echo $stats['inactive']; ?></div>
                                <div class="text-muted">Inactive Doctors</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <a href="add.php" class="btn btn-primary w-100">
                                    <i class="fas fa-user-plus"></i> Add New Doctor
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Filter Section -->
                    <div class="filter-section">
                        <form method="GET" action="" class="row g-3">
                            <div class="col-md-4">
                                <input type="text" class="form-control" name="search" 
                                       placeholder="Search by name, email, username..." 
                                       value="<?php echo escape($search); ?>">
                            </div>
                            <div class="col-md-2">
                                <select class="form-control" name="status">
                                    <option value="all" <?php echo $status == 'all' ? 'selected' : ''; ?>>All Status</option>
                                    <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="inactive" <?php echo $status == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <select class="form-control" name="plan">
                                    <option value="all" <?php echo $plan == 'all' ? 'selected' : ''; ?>>All Plans</option>
                                    <?php foreach($plans as $p): ?>
                                        <option value="<?php echo $p['plan_type']; ?>" <?php echo $plan == $p['plan_type'] ? 'selected' : ''; ?>>
                                            <?php echo ucfirst($p['plan_type']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-search"></i> Filter
                                </button>
                            </div>
                            <div class="col-md-2">
                                <a href="export.php?<?php echo http_build_query($_GET); ?>" class="btn btn-success w-100">
                                    <i class="fas fa-download"></i> Export CSV
                                </a>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Doctors Table -->
                    <div class="card">
                        <div class="card-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">Doctors List</h5>
                                <span class="badge bg-primary"><?php echo $totalDoctors; ?> Total</span>
                            </div>
                        </div>
                        <div class="card-body">
                            <form method="POST" id="bulkForm">
                                <div class="table-responsive">
                                    <table class="table table-bordered table-hover">
                                        <thead class="table-light">
                                            <tr>
                                                <th width="30">
                                                    <input type="checkbox" id="selectAll">
                                                </th>
                                                <th>ID</th>
                                                <th>Photo</th>
                                                <th>Doctor Details</th>
                                                <th>Contact</th>
                                                <th>Subscription</th>
                                                <th>Cases</th>
                                                <th>Status</th>
                                                <th>Joined</th>
                                                <th width="150">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (empty($doctors)): ?>
                                                <tr>
                                                    <td colspan="10" class="text-center text-muted py-4">
                                                        <i class="fas fa-user-md fa-2x mb-2 d-block"></i>
                                                        No doctors found
                                                    </td>
                                                </tr>
                                            <?php else: ?>
                                                <?php foreach($doctors as $doctor): ?>
                                                <tr>
                                                    <td>
                                                        <input type="checkbox" name="selected_ids[]" value="<?php echo $doctor['id']; ?>" class="doctor-checkbox">
                                                    </td>
                                                    <td><?php echo $doctor['id']; ?></td>
                                                    <td class="text-center">
                                                        <div class="rounded-circle bg-secondary text-white d-inline-flex align-items-center justify-content-center" 
                                                             style="width: 40px; height: 40px; font-size: 18px;">
                                                            <?php echo strtoupper(substr($doctor['full_name'], 0, 1)); ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <strong><?php echo escape($doctor['full_name']); ?></strong><br>
                                                        <small class="text-muted">@<?php echo $doctor['username']; ?></small>
                                                    </td>
                                                    <td>
                                                        <i class="fas fa-envelope"></i> <?php echo $doctor['email']; ?><br>
                                                        <small class="text-muted">
                                                            <i class="fas fa-calendar-alt"></i> 
                                                            Joined: <?php echo date(DISPLAY_DATE_FORMAT, strtotime($doctor['created_at'])); ?>
                                                        </small>
                                                    </td>
                                                    <td>
                                                        <?php if ($doctor['plan_type']): ?>
                                                            <span class="badge bg-info"><?php echo $doctor['plan_type']; ?></span><br>
                                                            <small>
                                                                <?php if ($doctor['days_remaining'] !== null && $doctor['days_remaining'] > 0): ?>
                                                                    <span class="text-success"><?php echo $doctor['days_remaining']; ?> days left</span>
                                                                <?php elseif ($doctor['days_remaining'] !== null && $doctor['days_remaining'] <= 0): ?>
                                                                    <span class="text-danger">Expired</span>
                                                                <?php else: ?>
                                                                    Unlimited
                                                                <?php endif; ?>
                                                            </small>
                                                        <?php else: ?>
                                                            <span class="text-muted">No active plan</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-secondary"><?php echo $doctor['total_cases']; ?> total</span><br>
                                                        <small class="text-success"><?php echo $doctor['active_cases']; ?> active</small>
                                                    </td>
                                                    <td>
                                                        <span class="status-badge <?php echo $doctor['is_active'] ? 'status-active' : 'status-inactive'; ?>">
                                                            <?php echo $doctor['is_active'] ? 'Active' : 'Inactive'; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php echo date('d-m-Y', strtotime($doctor['created_at'])); ?>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <a href="view.php?id=<?php echo $doctor['id']; ?>" class="btn btn-info" title="View">
                                                                <i class="fas fa-eye"></i>
                                                            </a>
                                                            <a href="edit.php?id=<?php echo $doctor['id']; ?>" class="btn btn-primary" title="Edit">
                                                                <i class="fas fa-edit"></i>
                                                            </a>
                                                            <a href="toggle-status.php?id=<?php echo $doctor['id']; ?>" 
                                                               class="btn btn-warning" title="<?php echo $doctor['is_active'] ? 'Deactivate' : 'Activate'; ?>"
                                                               onclick="return confirm('<?php echo $doctor['is_active'] ? 'Deactivate' : 'Activate'; ?> this doctor?')">
                                                                <i class="fas <?php echo $doctor['is_active'] ? 'fa-ban' : 'fa-check-circle'; ?>"></i>
                                                            </a>
                                                            <a href="delete.php?id=<?php echo $doctor['id']; ?>" 
                                                               class="btn btn-danger" title="Delete"
                                                               onclick="return confirm('Delete this doctor? This action cannot be undone.')">
                                                                <i class="fas fa-trash"></i>
                                                            </a>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                                
                                <!-- Bulk Actions -->
                                <?php if (!empty($doctors)): ?>
                                <div class="row mt-3">
                                    <div class="col-md-6">
                                        <div class="input-group">
                                            <select name="bulk_action" class="form-control w-auto" style="width: auto;">
                                                <option value="">Bulk Actions</option>
                                                <option value="activate">Activate Selected</option>
                                                <option value="deactivate">Deactivate Selected</option>
                                                <option value="delete">Delete Selected</option>
                                            </select>
                                            <button type="submit" class="btn btn-secondary" onclick="return confirmBulkAction()">
                                                Apply
                                            </button>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <?php echo pagination($page, $totalPages, 'index.php?' . http_build_query(array_merge($_GET, ['page' => 'PAGE']))); ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        // Select all checkbox functionality
        document.getElementById('selectAll')?.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.doctor-checkbox');
            checkboxes.forEach(cb => cb.checked = this.checked);
        });
        
        function confirmBulkAction() {
            const action = document.querySelector('[name="bulk_action"]').value;
            const checked = document.querySelectorAll('.doctor-checkbox:checked').length;
            
            if (!action) {
                alert('Please select an action');
                return false;
            }
            
            if (checked === 0) {
                alert('Please select at least one doctor');
                return false;
            }
            
            return confirm(`Are you sure you want to ${action} ${checked} doctor(s)?`);
        }
    </script>
</body>
</html>