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

$pdo = getDBConnection();
$error = '';
$success = '';

// Get all service requests with user info
$stmt = $pdo->query("
    SELECT sr.*, u.username, u.full_name as user_name, u.email as user_email, 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'] ?? '';
    
    try {
        $stmt = $pdo->prepare("UPDATE service_requests SET status = ?, admin_notes = ? WHERE id = ?");
        $stmt->execute([$newStatus, $adminNotes, $requestId]);
        $success = "Service request #$requestId updated to " . ucfirst($newStatus);
        
        // Refresh the data
        $stmt = $pdo->query("
            SELECT sr.*, u.username, u.full_name as user_name, u.email as user_email, 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();
    } catch (Exception $e) {
        $error = "Update failed: " . $e->getMessage();
    }
}

// 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();

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

if ($statusFilter !== 'all') {
    $stmt = $pdo->prepare("
        SELECT sr.*, u.username, u.full_name as user_name, u.email as user_email, 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();
}

if ($search) {
    $stmt = $pdo->prepare("
        SELECT sr.*, u.username, u.full_name as user_name, u.email as user_email, 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.company_name LIKE ? OR sr.company_email LIKE ? OR sr.service_type LIKE ?
        ORDER BY sr.created_at DESC
    ");
    $stmt->execute(["%$search%", "%$search%", "%$search%"]);
    $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 | Soul Guard</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;
        }
        
        .navbar{
            background:#13131a;
            border-bottom:1px solid rgba(255,255,255,0.06);
            padding:15px 30px;
            position:sticky;
            top:0;
            z-index:100;
        }
        
        .nav-container{
            max-width:1400px;
            margin:0 auto;
            display:flex;
            justify-content:space-between;
            align-items:center;
            flex-wrap:wrap;
            gap:15px;
        }
        
        .logo h2{
            background:linear-gradient(135deg,#06b6d4,#14b8a6);
            -webkit-background-clip:text;
            -webkit-text-fill-color:transparent;
            font-size:20px;
        }
        
        .nav-links{
            display:flex;
            gap:10px;
            align-items:center;
            flex-wrap:wrap;
        }
        
        .nav-links a{
            color:#a1a1aa;
            text-decoration:none;
            padding:8px 14px;
            border-radius:8px;
            transition:all 0.2s;
            font-size:13px;
        }
        
        .nav-links a:hover,.nav-links a.active{
            background:rgba(6,182,212,0.1);
            color:#06b6d4;
        }
        
        .container{
            max-width:1400px;
            margin:0 auto;
            padding:30px;
        }
        
        .page-header{
            margin-bottom:30px;
        }
        
        .page-header h1{
            font-size:28px;
            margin-bottom:8px;
        }
        
        .page-header p{
            color:#a1a1aa;
            font-size:14px;
        }
        
        .stats-grid{
            display:grid;
            grid-template-columns:repeat(auto-fit,minmax(180px,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:20px;
            text-align:center;
            transition:all 0.3s;
        }
        
        .stat-card:hover{
            transform:translateY(-2px);
            background:rgba(255,255,255,0.05);
        }
        
        .stat-number{
            font-size:32px;
            font-weight:800;
            color:#06b6d4;
        }
        
        .stat-label{
            font-size:12px;
            color:#a1a1aa;
            margin-top:8px;
        }
        
        .filter-bar{
            background:rgba(255,255,255,0.02);
            border:1px solid rgba(255,255,255,0.06);
            border-radius:12px;
            padding:15px 20px;
            margin-bottom:25px;
            display:flex;
            gap:10px;
            flex-wrap:wrap;
            align-items:center;
        }
        
        .filter-btn{
            padding:8px 16px;
            background:rgba(255,255,255,0.03);
            border:1px solid rgba(255,255,255,0.08);
            border-radius:8px;
            color:#a1a1aa;
            text-decoration:none;
            font-size:13px;
            transition:all 0.2s;
        }
        
        .filter-btn:hover,.filter-btn.active{
            background:rgba(6,182,212,0.15);
            border-color:#06b6d4;
            color:#06b6d4;
        }
        
        .search-box{
            flex:1;
            padding:8px 14px;
            background:rgba(0,0,0,0.3);
            border:1px solid rgba(255,255,255,0.08);
            border-radius:8px;
            color:#e4e4e7;
            font-size:13px;
        }
        
        .search-box:focus{
            outline:none;
            border-color:#06b6d4;
        }
        
        .alert{
            padding:12px 16px;
            border-radius:8px;
            margin-bottom:20px;
            font-size:13px;
        }
        
        .alert-success{
            background:rgba(34,197,94,0.1);
            border:1px solid rgba(34,197,94,0.3);
            color:#86efac;
        }
        
        .alert-error{
            background:rgba(239,68,68,0.1);
            border:1px solid rgba(239,68,68,0.3);
            color:#fca5a5;
        }
        
        .table-container{
            overflow-x:auto;
            background:rgba(255,255,255,0.02);
            border:1px solid rgba(255,255,255,0.06);
            border-radius:12px;
        }
        
        table{
            width:100%;
            border-collapse:collapse;
        }
        
        th,td{
            padding:14px 12px;
            text-align:left;
            border-bottom:1px solid rgba(255,255,255,0.06);
            vertical-align:top;
        }
        
        th{
            background:rgba(6,182,212,0.08);
            color:#06b6d4;
            font-weight:600;
            font-size:13px;
        }
        
        td{
            font-size:13px;
        }
        
        .status-badge{
            display:inline-block;
            padding:4px 10px;
            border-radius:20px;
            font-size:11px;
            font-weight:600;
        }
        
        .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 12px;
            border-radius:6px;
            font-size:11px;
            font-weight:500;
            cursor:pointer;
            border:none;
            transition:all 0.2s;
            text-decoration:none;
        }
        
        .btn-primary{
            background:rgba(6,182,212,0.15);
            color:#06b6d4;
            border:1px solid rgba(6,182,212,0.3);
        }
        
        .btn-primary:hover{
            background:rgba(6,182,212,0.25);
        }
        
        .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:30px;
            max-width:500px;
            width:90%;
        }
        
        .modal-header{
            display:flex;
            justify-content:space-between;
            align-items:center;
            margin-bottom:20px;
            padding-bottom:15px;
            border-bottom:1px solid rgba(255,255,255,0.08);
        }
        
        .modal-header h3{
            color:#06b6d4;
            font-size:18px;
        }
        
        .modal-close{
            cursor:pointer;
            font-size:24px;
            color:#a1a1aa;
        }
        
        .modal-close:hover{
            color:#ef4444;
        }
        
        .form-group{
            margin-bottom:20px;
        }
        
        .form-group label{
            display:block;
            margin-bottom:8px;
            font-size:12px;
            color:#a1a1aa;
            font-weight:500;
        }
        
        .form-group select,.form-group textarea{
            width:100%;
            padding:10px 12px;
            background:rgba(0,0,0,0.3);
            border:1px solid rgba(255,255,255,0.1);
            border-radius:8px;
            color:#e4e4e7;
            font-size:13px;
        }
        
        .form-group select:focus,.form-group textarea:focus{
            outline:none;
            border-color:#06b6d4;
        }
        
        .form-buttons{
            display:flex;
            gap:10px;
            justify-content:flex-end;
        }
        
        .btn-save{
            background:#06b6d4;
            color:#fff;
            padding:10px 20px;
            border:none;
            border-radius:8px;
            cursor:pointer;
            font-weight:600;
        }
        
        .btn-cancel{
            background:rgba(239,68,68,0.2);
            color:#ef4444;
            padding:10px 20px;
            border:none;
            border-radius:8px;
            cursor:pointer;
            font-weight:600;
        }
        
        .empty-state{
            text-align:center;
            padding:60px;
            color:#a1a1aa;
        }
        
        .message-preview{
            max-width:200px;
            white-space:nowrap;
            overflow:hidden;
            text-overflow:ellipsis;
        }
        
        .message-preview:hover{
            white-space:normal;
            overflow:visible;
        }
        
        .service-type{
            font-weight:600;
            color:#c4b5fd;
        }
        
        @media (max-width:768px){
            .container{padding:15px}
            .filter-bar{flex-direction:column}
            .search-box{width:100%}
            th,td{padding:8px;font-size:11px}
        }
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="nav-container">
            <div class="logo">
                <h2>🛡️ Soul Guard Admin</h2>
            </div>
            <div class="nav-links">
                <a href="index.php">📊 Dashboard</a>
                <a href="admin_services.php" class="active">📋 Service Requests</a>
                <a href="users.php">👥 Users</a>
                <a href="logout.php?logout=1">🚪 Logout</a>
            </div>
        </div>
    </nav>
    
    <div class="container">
        <div class="page-header">
            <h1>📋 Service Requests Management</h1>
            <p>View and manage all member service requests. Update status and add notes for members.</p>
        </div>
        
        <?php if($success): ?>
        <div class="alert alert-success">✅ <?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        
        <?php if($error): ?>
        <div class="alert alert-error">❌ <?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['total']; ?></div>
                <div class="stat-label">Total Requests</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['pending']; ?></div>
                <div class="stat-label">Pending</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['processing']; ?></div>
                <div class="stat-label">Processing</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['completed']; ?></div>
                <div class="stat-label">Completed</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['cancelled']; ?></div>
                <div class="stat-label">Cancelled</div>
            </div>
        </div>
        
        <!-- Filter Bar -->
        <div class="filter-bar">
            <a href="admin_services.php?status=all" class="filter-btn <?php echo $statusFilter == 'all' ? 'active' : ''; ?>">All</a>
            <a href="services.php?status=pending" class="filter-btn <?php echo $statusFilter == 'pending' ? 'active' : ''; ?>">Pending</a>
            <a href="services.php?status=processing" class="filter-btn <?php echo $statusFilter == 'processing' ? 'active' : ''; ?>">Processing</a>
            <a href="services.php?status=completed" class="filter-btn <?php echo $statusFilter == 'completed' ? 'active' : ''; ?>">Completed</a>
            <a href="services.php?status=cancelled" class="filter-btn <?php echo $statusFilter == 'cancelled' ? 'active' : ''; ?>">Cancelled</a>
            <form method="GET" style="flex:1;display:flex;gap:10px;margin-left:auto">
                <input type="hidden" name="status" value="<?php echo $statusFilter; ?>">
                <input type="text" name="search" class="search-box" placeholder="Search by company, email, or service..." value="<?php echo htmlspecialchars($search); ?>">
                <button type="submit" class="filter-btn">🔍 Search</button>
                <?php if($search): ?>
                <a href="services.php?status=<?php echo $statusFilter; ?>" class="filter-btn">Clear</a>
                <?php endif; ?>
            </form>
        </div>
        
        <!-- Service Requests Table -->
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Date</th>
                        <th>User</th>
                        <th>Organization</th>
                        <th>Service Type</th>
                        <th>Company Details</th>
                        <th>Message</th>
                        <th>Status</th>
                        <th>Admin Notes</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($serviceRequests)): ?>
                    <tr>
                        <td colspan="10" class="empty-state">
                            <div>📭 No service requests found</div>
                            <div style="font-size:12px;margin-top:10px">Members can request services from their dashboard</div>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach($serviceRequests as $request): ?>
                        <tr>
                            <td>#<?php echo $request['id']; ?></td>
                            <td><?php echo date('M d, Y', strtotime($request['created_at'])); ?><br><small><?php echo date('H:i', strtotime($request['created_at'])); ?></small></td>
                            <td>
                                <?php echo htmlspecialchars($request['username'] ?: $request['user_name']); ?><br>
                                <small><?php echo htmlspecialchars($request['user_email']); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($request['org_name'] ?: '-'); ?></td>
                            <td><span class="service-type"><?php echo htmlspecialchars($request['service_type']); ?></span></td>
                            <td>
                                <strong><?php echo htmlspecialchars($request['company_name']); ?></strong><br>
                                <small>📧 <?php echo htmlspecialchars($request['company_email']); ?></small><br>
                                <?php if($request['company_phone']): ?>
                                <small>📞 <?php echo htmlspecialchars($request['company_phone']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td class="message-preview" title="<?php echo htmlspecialchars($request['message']); ?>">
                                <?php echo htmlspecialchars(substr($request['message'] ?? '', 0, 60)); ?>
                                <?php if(strlen($request['message'] ?? '') > 60): ?>...<?php endif; ?>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $request['status']; ?>">
                                    <?php echo ucfirst($request['status']); ?>
                                </span>
                            </td>
                            <td class="message-preview" title="<?php echo htmlspecialchars($request['admin_notes']); ?>">
                                <?php echo htmlspecialchars(substr($request['admin_notes'] ?? '', 0, 50)); ?>
                                <?php if(strlen($request['admin_notes'] ?? '') > 50): ?>...<?php endif; ?>
                            </td>
                            <td>
                                <button class="btn btn-primary" onclick="openUpdateModal(<?php echo $request['id']; ?>, '<?php echo $request['status']; ?>', '<?php echo htmlspecialchars(addslashes($request['admin_notes'] ?? '')); ?>')">
                                    ✏️ Update
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Update Modal -->
    <div id="updateModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>✏️ Update Service Request</h3>
                <span class="modal-close" onclick="closeUpdateModal()">&times;</span>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="request_id" id="update_request_id">
                <input type="hidden" name="update_status" value="1">
                
                <div class="form-group">
                    <label>Status</label>
                    <select name="status" id="update_status" required>
                        <option value="pending">⏳ Pending - Awaiting processing</option>
                        <option value="processing">🔄 Processing - Being handled</option>
                        <option value="completed">✅ Completed - Service delivered</option>
                        <option value="cancelled">❌ Cancelled - Request cancelled</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Admin Notes (visible to member)</label>
                    <textarea name="admin_notes" id="update_notes" rows="4" placeholder="Add any notes, updates, or follow-up information for the member..."></textarea>
                </div>
                
                <div class="form-buttons">
                    <button type="submit" class="btn-save">💾 Save Changes</button>
                    <button type="button" class="btn-cancel" onclick="closeUpdateModal()">Cancel</button>
                </div>
            </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';
        }
        
        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('updateModal');
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        }
    </script>
</body>
</html>