<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_admin.php');
session_start();

if (!isset($_SESSION['SESS_ID_ADMIN'])) {
    header("Location: login.php");
    exit();
}

// Pagination settings
$perPage = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $perPage;

// Search parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$statusFilter = isset($_GET['status']) ? $_GET['status'] : '';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_status'])) {
        // Update status handler
        $complaint_id = (int)$_POST['complaint_id'];
        $status = $_POST['status'];
        $admin_notes = trim($_POST['admin_notes']);

        try {
            $stmt = $DBH->prepare("
                UPDATE tbl_complaints 
                SET status = ?, admin_notes = ?, updated_at = NOW() 
                WHERE id = ?
            ");
            $stmt->execute([$status, $admin_notes, $complaint_id]);
            
            $_SESSION['success_message'] = "Complaint updated successfully";
            header("Location: complaint_admin.php?page=".$page);
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error updating complaint: " . $e->getMessage();
        }
    } elseif (isset($_POST['delete_complaint'])) {
        // Delete handler
        $complaint_id = (int)$_POST['complaint_id'];
        
        try {
            $stmt = $DBH->prepare("DELETE FROM tbl_complaints WHERE id = ?");
            $stmt->execute([$complaint_id]);
            
            $_SESSION['success_message'] = "Complaint deleted successfully";
            header("Location: complaint_admin.php");
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error deleting complaint: " . $e->getMessage();
        }
    }
}

// Build query for complaints (remove the types variable as we don't need it for PDO)
$query = "SELECT * FROM tbl_complaints WHERE 1=1";
$params = [];

if (!empty($search)) {
    $query .= " AND (name LIKE ? OR email LIKE ? OR registration_no LIKE ? OR message LIKE ?)";
    $searchTerm = "%$search%";
    array_push($params, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
}

if (!empty($statusFilter) && in_array($statusFilter, ['Pending', 'In Progress', 'Resolved'])) {
    $query .= " AND status = ?";
    $params[] = $statusFilter;
}

// Get total count for pagination (unchanged)
$countStmt = $DBH->prepare(str_replace('*', 'COUNT(*)', $query));
$countStmt->execute($params);
$totalComplaints = $countStmt->fetchColumn();

// Add sorting and pagination
$query .= " ORDER BY 
    CASE status 
        WHEN 'Pending' THEN 1 
        WHEN 'In Progress' THEN 2 
        ELSE 3 
    END, 
    created_at DESC
    LIMIT ? OFFSET ?";

// Add pagination parameters (as integers)
$params[] = $perPage;
$params[] = $offset;

// Get complaints
$stmt = $DBH->prepare($query);

// Bind parameters properly - need to specify type for LIMIT and OFFSET
foreach ($params as $key => $value) {
    $paramType = PDO::PARAM_STR;
    // The last two parameters are LIMIT and OFFSET which should be integers
    if ($key >= count($params) - 2) {
        $paramType = PDO::PARAM_INT;
    }
    $stmt->bindValue($key + 1, $value, $paramType);
}

$stmt->execute();
$complaints = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate total pages
$totalPages = ceil($totalComplaints / $perPage);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Complaints - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background-color: #f8f9fa; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .status-badge { padding: 3px 8px; border-radius: 20px; font-size: 0.75rem; font-weight: 600; }
        .status-pending { background-color: #fff3cd; color: #856404; }
        .status-inprogress { background-color: #cce5ff; color: #004085; }
        .status-resolved { background-color: #d4edda; color: #155724; }
        .table-responsive { overflow-x: auto; }
        .search-box { max-width: 300px; }
        .pagination .page-item.active .page-link { background-color: #2E7D32; border-color: #2E7D32; }
        .pagination .page-link { color: #2E7D32; }
        .btn-outline-secondary {
        border-color: #6c757d;
        color: #6c757d;
    }
    .btn-outline-secondary:hover {
        background-color: #6c757d;
        color: white;
    }
    </style>
</head>
<body>
    <?php include('header.php'); ?>
    
<div class="container py-4">
    <!-- Header with Back Button -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <a href="main.php" class="btn btn-outline-secondary me-2">
                <i class="fas fa-arrow-left"></i> Back to Dashboard
            </a>
            <h2 class="d-inline-block mb-0">Manage Complaints</h2>
        </div>
        <a href="complaint_export.php" class="btn btn-outline-success">
            <i class="fas fa-download"></i> Export
        </a>
    </div>
    
    <!-- Messages -->
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success"><?= $_SESSION['success_message'] ?></div>
        <?php unset($_SESSION['success_message']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger"><?= $_SESSION['error_message'] ?></div>
        <?php unset($_SESSION['error_message']); ?>
    <?php endif; ?>

        <!-- Search and Filter Form -->
        <form method="GET" class="mb-4">
            <div class="row g-3">
                <div class="col-md-5">
                    <div class="input-group">
                        <input type="text" name="search" class="form-control" placeholder="Search complaints..." 
                               value="<?= htmlspecialchars($search) ?>">
                        <button class="btn btn-success" type="submit">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </div>
                <div class="col-md-4">
                    <select name="status" class="form-select" onchange="this.form.submit()">
                        <option value="">All Statuses</option>
                        <option value="Pending" <?= $statusFilter === 'Pending' ? 'selected' : '' ?>>Pending</option>
                        <option value="In Progress" <?= $statusFilter === 'In Progress' ? 'selected' : '' ?>>In Progress</option>
                        <option value="Resolved" <?= $statusFilter === 'Resolved' ? 'selected' : '' ?>>Resolved</option>
                    </select>
                </div>
                <div class="col-md-3 text-end">
                    <a href="complaint_admin.php" class="btn btn-outline-secondary">Reset Filters</a>
                </div>
            </div>
        </form>

        <!-- Complaints Table -->
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($complaints as $complaint): ?>
                        <tr>
                            <td><?= $complaint['id'] ?></td>
                            <td><?= htmlspecialchars($complaint['name']) ?></td>
                            <td><?= htmlspecialchars($complaint['email']) ?></td>
                            <td><?= htmlspecialchars($complaint['complaint_type']) ?></td>
                            <td>
                                <span class="status-badge status-<?= strtolower(str_replace(' ', '', $complaint['status'])) ?>">
                                    <?= $complaint['status'] ?>
                                </span>
                            </td>
                            <td><?= date('M j, Y', strtotime($complaint['created_at'])) ?></td>
                            <td>
                                <div class="d-flex gap-2">
                                    <!-- View Button -->
                                    <button type="button" class="btn btn-sm btn-info" data-bs-toggle="modal" 
                                            data-bs-target="#viewModal<?= $complaint['id'] ?>">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    
                                    <!-- Edit Button -->
                                    <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" 
                                            data-bs-target="#editModal<?= $complaint['id'] ?>">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    
                                    <!-- Delete Button -->
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="complaint_id" value="<?= $complaint['id'] ?>">
                                        <button type="submit" name="delete_complaint" class="btn btn-sm btn-danger" 
                                                onclick="return confirm('Are you sure you want to delete this complaint?')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>

                        <!-- View Modal -->
                        <div class="modal fade" id="viewModal<?= $complaint['id'] ?>" tabindex="-1" aria-hidden="true">
                            <div class="modal-dialog modal-lg">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title">Complaint Details #<?= $complaint['id'] ?></h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <p><strong>Name:</strong> <?= htmlspecialchars($complaint['name']) ?></p>
                                            </div>
                                            <div class="col-md-6">
                                                <p><strong>Email:</strong> <?= htmlspecialchars($complaint['email']) ?></p>
                                            </div>
                                        </div>
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <p><strong>Admission No:</strong> <?= $complaint['registration_no'] ? htmlspecialchars($complaint['registration_no']) : 'N/A' ?></p>
                                            </div>
                                            <div class="col-md-6">
                                                <p><strong>Type:</strong> <?= htmlspecialchars($complaint['complaint_type']) ?></p>
                                            </div>
                                        </div>
                                        <div class="mb-3">
                                            <p><strong>Message:</strong></p>
                                            <div class="p-3 bg-light rounded">
                                                <?= nl2br(htmlspecialchars($complaint['message'])) ?>
                                            </div>
                                        </div>
                                        <?php if ($complaint['admin_notes']): ?>
                                            <div class="mb-3">
                                                <p><strong>Admin Notes:</strong></p>
                                                <div class="p-3 bg-light rounded">
                                                    <?= nl2br(htmlspecialchars($complaint['admin_notes'])) ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <p><strong>Created:</strong> <?= date('M j, Y g:i A', strtotime($complaint['created_at'])) ?></p>
                                            </div>
                                            <div class="col-md-6">
                                                <p><strong>Last Updated:</strong> <?= $complaint['updated_at'] ? date('M j, Y g:i A', strtotime($complaint['updated_at'])) : 'Never' ?></p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Edit Modal -->
                        <div class="modal fade" id="editModal<?= $complaint['id'] ?>" tabindex="-1" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <form method="POST">
                                        <div class="modal-header">
                                            <h5 class="modal-title">Update Complaint #<?= $complaint['id'] ?></h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <input type="hidden" name="complaint_id" value="<?= $complaint['id'] ?>">
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Status</label>
                                                <select name="status" class="form-select" required>
                                                    <option value="Pending" <?= $complaint['status'] === 'Pending' ? 'selected' : '' ?>>Pending</option>
                                                    <option value="In Progress" <?= $complaint['status'] === 'In Progress' ? 'selected' : '' ?>>In Progress</option>
                                                    <option value="Resolved" <?= $complaint['status'] === 'Resolved' ? 'selected' : '' ?>>Resolved</option>
                                                </select>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Admin Notes</label>
                                                <textarea name="admin_notes" class="form-control" rows="4"><?= htmlspecialchars($complaint['admin_notes'] ?? '') ?></textarea>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                            <button type="submit" name="update_status" class="btn btn-primary">Save Changes</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    
                    <?php if (empty($complaints)): ?>
                        <tr>
                            <td colspan="7" class="text-center py-4">No complaints found</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center mt-4">
                    <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                        <a class="page-link" href="?page=1&search=<?= urlencode($search) ?>&status=<?= urlencode($statusFilter) ?>">
                            <i class="fas fa-angle-double-left"></i>
                        </a>
                    </li>
                    <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                        <a class="page-link" href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($statusFilter) ?>">
                            <i class="fas fa-angle-left"></i>
                        </a>
                    </li>
                    
                    <?php 
                    // Show limited page numbers
                    $start = max(1, $page - 2);
                    $end = min($totalPages, $page + 2);
                    
                    for ($i = $start; $i <= $end; $i++): ?>
                        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                            <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($statusFilter) ?>">
                                <?= $i ?>
                            </a>
                        </li>
                    <?php endfor; ?>
                    
                    <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
                        <a class="page-link" href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($statusFilter) ?>">
                            <i class="fas fa-angle-right"></i>
                        </a>
                    </li>
                    <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
                        <a class="page-link" href="?page=<?= $totalPages ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($statusFilter) ?>">
                            <i class="fas fa-angle-double-right"></i>
                        </a>
                    </li>
                </ul>
            </nav>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-focus search field
        document.addEventListener('DOMContentLoaded', function() {
            const searchField = document.querySelector('input[name="search"]');
            if (searchField) searchField.focus();
        });
    </script>
</body>
</html>