<?php
// admin_services.php - Admin view of all service requests
require_once 'config.php';
requireAdmin();

$pdo = getDBConnection();

// Get all service requests with user info
$stmt = $pdo->query("
    SELECT sr.*, u.username, u.full_name as user_name, o.name as org_name
    FROM service_requests sr
    LEFT JOIN users u ON sr.user_id = u.id
    LEFT JOIN organizations o ON sr.organization_id = o.id
    ORDER BY sr.created_at DESC
");
$serviceRequests = $stmt->fetchAll();

// Update status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $requestId = $_POST['request_id'];
    $newStatus = $_POST['status'];
    $adminNotes = $_POST['admin_notes'] ?? '';
    
    // Make sure the table exists and columns are correct
try {
    $stmt = $pdo->prepare("UPDATE service_requests SET status = ?, admin_notes = ? WHERE id = ?");
    $stmt->execute([$newStatus, $adminNotes, $requestId]);
} catch (Exception $e) {
    // If admin_notes column doesn't exist in this context, try without it
    $stmt = $pdo->prepare("UPDATE service_requests SET status = ? WHERE id = ?");
    $stmt->execute([$newStatus, $requestId]);
}
    
    header('Location: admin_services.php?msg=updated');
    exit;
}

// Get statistics
$stats = [];
$stats['total'] = count($serviceRequests);
$stats['pending'] = $pdo->query("SELECT COUNT(*) FROM service_requests WHERE status = 'pending'")->fetchColumn();
$stats['processing'] = $pdo->query("SELECT COUNT(*) FROM service_requests WHERE status = 'processing'")->fetchColumn();
$stats['completed'] = $pdo->query("SELECT COUNT(*) FROM service_requests WHERE status = 'completed'")->fetchColumn();
$stats['cancelled'] = $pdo->query("SELECT COUNT(*) FROM service_requests WHERE status = 'cancelled'")->fetchColumn();

$statusFilter = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';

if ($statusFilter !== 'all') {
    $stmt = $pdo->prepare("
        SELECT sr.*, u.username, u.full_name as user_name, o.name as org_name
        FROM service_requests sr
        LEFT JOIN users u ON sr.user_id = u.id
        LEFT JOIN organizations o ON sr.organization_id = o.id
        WHERE sr.status = ?
        ORDER BY sr.created_at DESC
    ");
    $stmt->execute([$statusFilter]);
    $serviceRequests = $stmt->fetchAll();
}

$theme = getTheme();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Service Requests</title>
    <style>
        *{margin:0;padding:0;box-sizing:border-box}
        body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#0a0a0f;color:#e4e4e7}
        .container{max-width:1400px;margin:0 auto;padding:20px}
        .navbar{background:#13131a;border-bottom:1px solid rgba(255,255,255,0.06);padding:15px 30px;margin-bottom:30px}
        .navbar a{color:#a1a1aa;text-decoration:none;margin-right:20px}
        .navbar a:hover{color:#06b6d4}
        .stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:15px;margin-bottom:30px}
        .stat-card{background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06);border-radius:12px;padding:15px;text-align:center}
        .stat-number{font-size:28px;font-weight:800;color:#06b6d4}
        .filter-bar{background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06);border-radius:12px;padding:15px;margin-bottom:20px;display:flex;gap:10px;flex-wrap:wrap;align-items:center}
        .filter-btn{padding:8px 16px;background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.1);border-radius:8px;color:#a1a1aa;text-decoration:none}
        .filter-btn.active,.filter-btn:hover{background:rgba(6,182,212,0.2);border-color:#06b6d4;color:#06b6d4}
        .search-box{flex:1;padding:8px 16px;background:rgba(0,0,0,0.3);border:1px solid rgba(255,255,255,0.1);border-radius:8px;color:#e4e4e7}
        table{width:100%;border-collapse:collapse;background:rgba(255,255,255,0.02);border-radius:12px;overflow:hidden}
        th,td{padding:12px;text-align:left;border-bottom:1px solid rgba(255,255,255,0.06);vertical-align:top}
        th{background:rgba(6,182,212,0.1);color:#06b6d4}
        .status-badge{padding:4px 10px;border-radius:20px;font-size:11px;font-weight:600;display:inline-block}
        .status-pending{background:rgba(245,158,11,0.2);color:#fde047}
        .status-processing{background:rgba(59,130,246,0.2);color:#93c5fd}
        .status-completed{background:rgba(34,197,94,0.2);color:#86efac}
        .status-cancelled{background:rgba(239,68,68,0.2);color:#fca5a5}
        .btn{display:inline-block;padding:5px 10px;border-radius:5px;font-size:11px;cursor:pointer;border:none;margin:2px}
        .btn-primary{background:rgba(6,182,212,0.2);color:#06b6d4;border:1px solid rgba(6,182,212,0.3)}
        .btn-success{background:rgba(34,197,94,0.2);color:#22c55e;border:1px solid rgba(34,197,94,0.3)}
        .btn-danger{background:rgba(239,68,68,0.2);color:#ef4444;border:1px solid rgba(239,68,68,0.3)}
        .modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.95);z-index:1000;justify-content:center;align-items:center}
        .modal-content{background:#13131a;border:1px solid rgba(255,255,255,0.1);border-radius:16px;padding:25px;max-width:500px;width:90%}
        .form-group{margin-bottom:15px}
        .form-group label{display:block;margin-bottom:5px;font-size:12px;color:#a1a1aa}
        .form-group select,.form-group textarea{width:100%;padding:8px 12px;background:rgba(0,0,0,0.3);border:1px solid rgba(255,255,255,0.1);border-radius:6px;color:#e4e4e7}
    </style>
</head>
<body>
    <div class="navbar">
        <div class="container" style="padding:0">
            <a href="dashboard.php">🏠 Dashboard</a>
            <a href="admin_services.php" style="color:#06b6d4">📋 Service Requests</a>
            <a href="admin_users.php">👥 Users</a>
            <a href="index.php?logout=1" style="color:#ef4444">🚪 Logout</a>
        </div>
    </div>
    
    <div class="container">
        <h2>📋 Service Requests Management</h2>
        <p style="color:#a1a1aa;margin-bottom:20px">View and manage all member service requests</p>
        
        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card"><div class="stat-number"><?php echo $stats['total']; ?></div><div>Total Requests</div></div>
            <div class="stat-card"><div class="stat-number"><?php echo $stats['pending']; ?></div><div>Pending</div></div>
            <div class="stat-card"><div class="stat-number"><?php echo $stats['processing']; ?></div><div>Processing</div></div>
            <div class="stat-card"><div class="stat-number"><?php echo $stats['completed']; ?></div><div>Completed</div></div>
            <div class="stat-card"><div class="stat-number"><?php echo $stats['cancelled']; ?></div><div>Cancelled</div></div>
        </div>
        
        <!-- Filters -->
        <div class="filter-bar">
            <a href="admin_services.php?status=all" class="filter-btn <?php echo $statusFilter == 'all' ? 'active' : ''; ?>">All</a>
            <a href="admin_services.php?status=pending" class="filter-btn <?php echo $statusFilter == 'pending' ? 'active' : ''; ?>">Pending</a>
            <a href="admin_services.php?status=processing" class="filter-btn <?php echo $statusFilter == 'processing' ? 'active' : ''; ?>">Processing</a>
            <a href="admin_services.php?status=completed" class="filter-btn <?php echo $statusFilter == 'completed' ? 'active' : ''; ?>">Completed</a>
            <a href="admin_services.php?status=cancelled" class="filter-btn <?php echo $statusFilter == 'cancelled' ? 'active' : ''; ?>">Cancelled</a>
            <form method="GET" style="flex:1;display:flex;gap:10px">
                <input type="hidden" name="status" value="<?php echo $statusFilter; ?>">
                <input type="text" name="search" class="search-box" placeholder="Search by company or email..." value="<?php echo htmlspecialchars($search); ?>">
                <button type="submit" class="filter-btn">Search</button>
            </form>
        </div>
        
        <!-- Table -->
        <table>
            <thead>
                <tr><th>ID</th><th>Date</th><th>User</th><th>Organization</th><th>Service Type</th><th>Company</th><th>Status</th><th>Actions</th></tr>
            </thead>
            <tbody>
                <?php foreach($serviceRequests as $request): ?>
                <tr>
                    <td><?php echo $request['id']; ?></td>
                    <td><?php echo date('M d, H:i', strtotime($request['created_at'])); ?></td>
                    <td><?php echo htmlspecialchars($request['username'] ?: $request['user_name']); ?></td>
                    <td><?php echo htmlspecialchars($request['org_name'] ?: '-'); ?></td>
                    <td><?php echo htmlspecialchars($request['service_type']); ?></td>
                    <td><?php echo htmlspecialchars($request['company_name']); ?><br><small><?php echo htmlspecialchars($request['company_email']); ?></small></td>
                    <td><span class="status-badge status-<?php echo $request['status']; ?>"><?php echo ucfirst($request['status']); ?></span></td>
                    <td>
                        <button class="btn btn-primary" onclick="openUpdateModal(<?php echo $request['id']; ?>, '<?php echo $request['status']; ?>', '<?php echo addslashes($request['admin_notes'] ?? ''); ?>')">Update</button>
                        <?php if($request['message']): ?>
                        <button class="btn btn-primary" onclick="alert('Message: <?php echo addslashes($request['message']); ?>')">View Message</button>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if(empty($serviceRequests)): ?>
                <tr><td colspan="8" style="text-align:center;padding:40px">No service requests found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- Update Modal -->
    <div id="updateModal" class="modal">
        <div class="modal-content">
            <h3 style="margin-bottom:15px">Update Service Request</h3>
            <form method="POST" action="">
                <input type="hidden" name="request_id" id="update_request_id">
                <div class="form-group">
                    <label>Status</label>
                    <select name="status" id="update_status">
                        <option value="pending">Pending</option>
                        <option value="processing">Processing</option>
                        <option value="completed">Completed</option>
                        <option value="cancelled">Cancelled</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Admin Notes (visible to member)</label>
                    <textarea name="admin_notes" id="update_notes" rows="3" placeholder="Add any notes or updates for the member..."></textarea>
                </div>
                <button type="submit" name="update_status" class="btn" style="background:#06b6d4;color:#fff;padding:10px 20px">Update Request</button>
                <button type="button" class="btn" onclick="closeUpdateModal()" style="background:#ef4444;color:#fff">Cancel</button>
            </form>
        </div>
    </div>
    
    <script>
        function openUpdateModal(id, status, notes) {
            document.getElementById('update_request_id').value = id;
            document.getElementById('update_status').value = status;
            document.getElementById('update_notes').value = notes;
            document.getElementById('updateModal').style.display = 'flex';
        }
        
        function closeUpdateModal() {
            document.getElementById('updateModal').style.display = 'none';
        }
        
        window.onclick = function(event) {
            const modal = document.getElementById('updateModal');
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        }
    </script>
</body>
</html>