<?php
session_start();
require_once '../db_connect.php';

if(!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header('Location: ../login');
    exit;
}

$admin_id = $_SESSION['user_id'];
$message = '';

// Handle actions
if(isset($_POST['action'])) {
    $alert_id = intval($_POST['alert_id']);
    $action = $_POST['action'];

    if($action == 'resolve') {
        $notes = mysqli_real_escape_string($conn, $_POST['notes'] ?? '');
        mysqli_query($conn, "UPDATE overlap_alerts SET is_resolved = 1, status = 'resolved',
            resolved_by = $admin_id, resolution_notes = '$notes', resolved_at = NOW()
            WHERE id = $alert_id");
        $message = 'Alert marked as resolved';
    } elseif($action == 'dismiss') {
        mysqli_query($conn, "UPDATE overlap_alerts SET is_resolved = 1, status = 'dismissed',
            resolved_by = $admin_id, resolved_at = NOW() WHERE id = $alert_id");
        $message = 'Alert dismissed';
    } elseif($action == 'investigate') {
        mysqli_query($conn, "UPDATE overlap_alerts SET status = 'investigating' WHERE id = $alert_id");
        $message = 'Alert marked for investigation';
    }
}

// Filter
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
$where = "1=1";
if($filter == 'pending') $where = "oa.status = 'pending'";
elseif($filter == 'investigating') $where = "oa.status = 'investigating'";
elseif($filter == 'resolved') $where = "oa.status = 'resolved'";
elseif($filter == 'dismissed') $where = "oa.status = 'dismissed'";

$alerts = mysqli_query($conn, "
    SELECT oa.*, l1.land_name as land1_name, l1.location_address as land1_address, l1.total_area as land1_area,
           l2.land_name as land2_name, l2.location_address as land2_address, l2.total_area as land2_area,
           u1.username as user1, u1.full_name as user1_name, u1.email as user1_email,
           u2.username as user2, u2.full_name as user2_name, u2.email as user2_email,
           ra.username as resolved_by_name
    FROM overlap_alerts oa
    JOIN lands l1 ON oa.land_id_1 = l1.id
    JOIN lands l2 ON oa.land_id_2 = l2.id
    JOIN users u1 ON l1.user_id = u1.id
    JOIN users u2 ON l2.user_id = u2.id
    LEFT JOIN users ra ON oa.resolved_by = ra.id
    WHERE $where
    ORDER BY oa.created_at DESC
");

$pending_count = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as c FROM overlap_alerts WHERE status = 'pending'"))['c'];
$investigating_count = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as c FROM overlap_alerts WHERE status = 'investigating'"))['c'];
$resolved_count = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as c FROM overlap_alerts WHERE status = 'resolved'"))['c'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Overlap Alerts - Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="admin-main">
        <!-- Page Header -->
        <div class="page-header">
            <div class="page-header-content">
                <div class="page-title">
                    <h1><i class="fas fa-exclamation-triangle"></i> Overlap Alerts</h1>
                    <p>Manage land boundary overlap alerts and conflicts</p>
                </div>
            </div>
        </div>

        <?php if($message): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle mr-2"></i><?php echo $message; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-icon orange">
                    <i class="fas fa-clock"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo $pending_count; ?></h3>
                    <p>Pending</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon blue">
                    <i class="fas fa-search"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo $investigating_count; ?></h3>
                    <p>Investigating</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon green">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo $resolved_count; ?></h3>
                    <p>Resolved</p>
                </div>
            </div>
        </div>

        <!-- Filter Tabs -->
        <div class="filter-tabs">
            <a href="alerts" class="filter-tab <?php echo $filter == 'all' ? 'active' : ''; ?>">
                <i class="fas fa-list"></i> All Alerts
            </a>
            <a href="alerts?filter=pending" class="filter-tab <?php echo $filter == 'pending' ? 'active' : ''; ?>">
                <i class="fas fa-clock"></i> Pending
                <?php if($pending_count > 0): ?><span class="badge"><?php echo $pending_count; ?></span><?php endif; ?>
            </a>
            <a href="alerts?filter=investigating" class="filter-tab <?php echo $filter == 'investigating' ? 'active' : ''; ?>">
                <i class="fas fa-search"></i> Investigating
            </a>
            <a href="alerts?filter=resolved" class="filter-tab <?php echo $filter == 'resolved' ? 'active' : ''; ?>">
                <i class="fas fa-check"></i> Resolved
            </a>
            <a href="alerts?filter=dismissed" class="filter-tab <?php echo $filter == 'dismissed' ? 'active' : ''; ?>">
                <i class="fas fa-times"></i> Dismissed
            </a>
        </div>

        <?php if(mysqli_num_rows($alerts) > 0): ?>
            <?php while($alert = mysqli_fetch_assoc($alerts)): ?>
            <div class="alert-card alert-<?php echo $alert['status']; ?>">
                <div class="alert-header">
                    <div class="alert-status-info">
                        <span class="status-badge status-<?php echo $alert['status']; ?>">
                            <?php echo ucfirst($alert['status']); ?>
                        </span>
                        <h4>Potential Overlap Detected</h4>
                        <span class="alert-date">
                            <i class="fas fa-calendar mr-1"></i>
                            Detected: <?php echo date('M d, Y H:i', strtotime($alert['created_at'])); ?>
                        </span>
                    </div>
                </div>

                <div class="alert-body">
                    <div class="lands-comparison">
                        <div class="land-box">
                            <div class="land-header">
                                <i class="fas fa-map-marker-alt"></i>
                                <span>Land 1</span>
                            </div>
                            <h5><?php echo htmlspecialchars($alert['land1_name']); ?></h5>
                            <div class="land-details">
                                <p><i class="fas fa-user"></i> <?php echo htmlspecialchars($alert['user1_name'] ?: $alert['user1']); ?></p>
                                <p><i class="fas fa-envelope"></i> <?php echo $alert['user1_email']; ?></p>
                                <p><i class="fas fa-ruler-combined"></i> <?php echo number_format($alert['land1_area'], 2); ?> sqm</p>
                            </div>
                            <a href="../view_land.php?id=<?php echo $alert['land_id_1']; ?>" target="_blank" class="btn-view-land">
                                <i class="fas fa-eye"></i> View Land
                            </a>
                        </div>

                        <div class="overlap-indicator">
                            <i class="fas fa-exchange-alt"></i>
                        </div>

                        <div class="land-box">
                            <div class="land-header">
                                <i class="fas fa-map-marker-alt"></i>
                                <span>Land 2</span>
                            </div>
                            <h5><?php echo htmlspecialchars($alert['land2_name']); ?></h5>
                            <div class="land-details">
                                <p><i class="fas fa-user"></i> <?php echo htmlspecialchars($alert['user2_name'] ?: $alert['user2']); ?></p>
                                <p><i class="fas fa-envelope"></i> <?php echo $alert['user2_email']; ?></p>
                                <p><i class="fas fa-ruler-combined"></i> <?php echo number_format($alert['land2_area'], 2); ?> sqm</p>
                            </div>
                            <a href="../view_land.php?id=<?php echo $alert['land_id_2']; ?>" target="_blank" class="btn-view-land">
                                <i class="fas fa-eye"></i> View Land
                            </a>
                        </div>
                    </div>

                    <?php if($alert['resolution_notes']): ?>
                    <div class="resolution-notes">
                        <strong><i class="fas fa-sticky-note mr-2"></i>Resolution Notes:</strong>
                        <p><?php echo nl2br(htmlspecialchars($alert['resolution_notes'])); ?></p>
                        <span class="resolved-info">
                            Resolved by: <?php echo $alert['resolved_by_name']; ?> on <?php echo date('M d, Y', strtotime($alert['resolved_at'])); ?>
                        </span>
                    </div>
                    <?php endif; ?>

                    <?php if($alert['status'] == 'pending' || $alert['status'] == 'investigating'): ?>
                    <div class="alert-actions">
                        <?php if($alert['status'] == 'pending'): ?>
                        <form method="POST" class="action-form">
                            <input type="hidden" name="alert_id" value="<?php echo $alert['id']; ?>">
                            <input type="hidden" name="action" value="investigate">
                            <button type="submit" class="btn-investigate">
                                <i class="fas fa-search"></i> Investigate
                            </button>
                        </form>
                        <?php endif; ?>

                        <button class="btn-resolve" data-toggle="modal"
                                data-target="#resolveModal" data-alertid="<?php echo $alert['id']; ?>">
                            <i class="fas fa-check"></i> Resolve
                        </button>

                        <form method="POST" class="action-form" onsubmit="return confirm('Dismiss this alert?')">
                            <input type="hidden" name="alert_id" value="<?php echo $alert['id']; ?>">
                            <input type="hidden" name="action" value="dismiss">
                            <button type="submit" class="btn-dismiss">
                                <i class="fas fa-times"></i> Dismiss
                            </button>
                        </form>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endwhile; ?>
        <?php else: ?>
        <div class="empty-state">
            <div class="empty-icon">
                <i class="fas fa-check-circle"></i>
            </div>
            <h3>No Alerts Found</h3>
            <p>No overlap alerts found for this filter.</p>
        </div>
        <?php endif; ?>
    </main>

    <!-- Resolve Modal -->
    <div class="modal fade" id="resolveModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fas fa-check-circle mr-2"></i>Resolve Alert</h5>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="alert_id" id="resolveAlertId">
                        <input type="hidden" name="action" value="resolve">
                        <div class="form-group">
                            <label>Resolution Notes</label>
                            <textarea name="notes" class="form-control" rows="4"
                                      placeholder="Describe how this was resolved..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">Mark as Resolved</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <style>
    /* Page-specific styles */
    .page-header {
        background: linear-gradient(135deg, #f5af19 0%, #f12711 100%);
        border-radius: 20px;
        padding: 30px;
        margin-bottom: 30px;
        color: white;
    }

    .page-title h1 {
        font-size: 28px;
        font-weight: 700;
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .page-title p {
        margin: 0;
        opacity: 0.9;
        font-size: 15px;
    }

    .stats-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }

    .stat-card {
        background: white;
        border-radius: 16px;
        padding: 24px;
        display: flex;
        align-items: center;
        gap: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.05);
    }

    .stat-icon {
        width: 56px;
        height: 56px;
        border-radius: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;
    }

    .stat-icon.orange {
        background: linear-gradient(135deg, #f5af19 0%, #f12711 100%);
    }

    .stat-icon.blue {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    .stat-icon.green {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    }

    .stat-info h3 {
        font-size: 24px;
        font-weight: 700;
        margin: 0;
        color: #1e293b;
    }

    .stat-info p {
        margin: 4px 0 0 0;
        color: #64748b;
        font-size: 14px;
    }

    .filter-tabs {
        display: flex;
        gap: 10px;
        margin-bottom: 25px;
        flex-wrap: wrap;
    }

    .filter-tab {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 18px;
        background: white;
        border-radius: 12px;
        text-decoration: none;
        color: #64748b;
        font-weight: 500;
        font-size: 14px;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    }

    .filter-tab:hover {
        background: #f8fafc;
        color: #f5af19;
        text-decoration: none;
        transform: translateY(-2px);
    }

    .filter-tab.active {
        background: linear-gradient(135deg, #f5af19 0%, #f12711 100%);
        color: white;
    }

    .filter-tab .badge {
        background: rgba(255,255,255,0.2);
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 11px;
    }

    .alert-card {
        background: white;
        border-radius: 20px;
        margin-bottom: 20px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.05);
        overflow: hidden;
        border-left: 4px solid #fbbf24;
    }

    .alert-card.alert-resolved {
        border-left-color: #22c55e;
        opacity: 0.85;
    }

    .alert-card.alert-dismissed {
        border-left-color: #94a3b8;
        opacity: 0.7;
    }

    .alert-card.alert-investigating {
        border-left-color: #667eea;
    }

    .alert-header {
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;
    }

    .alert-status-info {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 12px;
    }

    .alert-status-info h4 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #1e293b;
    }

    .alert-date {
        color: #64748b;
        font-size: 13px;
    }

    .status-badge {
        padding: 6px 14px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    .status-pending {
        background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
        color: white;
    }

    .status-investigating {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    .status-resolved {
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        color: white;
    }

    .status-dismissed {
        background: #94a3b8;
        color: white;
    }

    .alert-body {
        padding: 24px;
    }

    .lands-comparison {
        display: grid;
        grid-template-columns: 1fr auto 1fr;
        gap: 24px;
        align-items: center;
    }

    .land-box {
        background: #f8fafc;
        border-radius: 16px;
        padding: 20px;
    }

    .land-header {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #64748b;
        font-size: 13px;
        margin-bottom: 8px;
    }

    .land-box h5 {
        font-size: 16px;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 12px 0;
    }

    .land-details p {
        margin: 6px 0;
        font-size: 13px;
        color: #64748b;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .land-details i {
        width: 16px;
        color: #94a3b8;
    }

    .btn-view-land {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 8px 14px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px;
        text-decoration: none;
        font-size: 13px;
        font-weight: 500;
        margin-top: 12px;
        transition: all 0.3s ease;
    }

    .btn-view-land:hover {
        color: white;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }

    .overlap-indicator {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: linear-gradient(135deg, #f5af19 0%, #f12711 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 20px;
    }

    .resolution-notes {
        background: rgba(34, 197, 94, 0.1);
        border-radius: 12px;
        padding: 16px;
        margin-top: 20px;
        border-left: 4px solid #22c55e;
    }

    .resolution-notes strong {
        color: #166534;
    }

    .resolution-notes p {
        margin: 8px 0;
        color: #1e293b;
    }

    .resolved-info {
        font-size: 12px;
        color: #64748b;
    }

    .alert-actions {
        display: flex;
        gap: 12px;
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #f1f5f9;
    }

    .action-form {
        display: inline;
    }

    .btn-investigate, .btn-resolve, .btn-dismiss {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 10px 18px;
        border-radius: 10px;
        font-size: 14px;
        font-weight: 600;
        border: none;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-investigate {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    .btn-resolve {
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        color: white;
    }

    .btn-dismiss {
        background: #e2e8f0;
        color: #64748b;
    }

    .btn-investigate:hover, .btn-resolve:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }

    .btn-dismiss:hover {
        background: #cbd5e1;
    }

    .empty-state {
        background: white;
        border-radius: 20px;
        padding: 60px 40px;
        text-align: center;
        box-shadow: 0 4px 20px rgba(0,0,0,0.05);
    }

    .empty-icon {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 24px;
    }

    .empty-icon i {
        font-size: 36px;
        color: white;
    }

    .empty-state h3 {
        font-size: 22px;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 8px 0;
    }

    .empty-state p {
        color: #64748b;
        margin: 0;
    }

    .modal-content {
        border: none;
        border-radius: 20px;
    }

    .modal-header {
        border-bottom: 1px solid #f1f5f9;
        padding: 20px 24px;
    }

    .modal-body {
        padding: 24px;
    }

    .modal-footer {
        border-top: 1px solid #f1f5f9;
        padding: 16px 24px;
    }

    .form-control {
        border-radius: 12px;
        border: 2px solid #e2e8f0;
        padding: 12px 16px;
    }

    .form-control:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
    }

    .btn {
        border-radius: 10px;
        padding: 10px 20px;
        font-weight: 600;
    }

    .btn-success {
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        border: none;
    }

    .alert {
        border: none;
        border-radius: 14px;
        padding: 16px 20px;
        margin-bottom: 25px;
    }

    .alert-success {
        background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, rgba(22, 163, 74, 0.1) 100%);
        color: #166534;
        border-left: 4px solid #22c55e;
    }

    @media (max-width: 768px) {
        .page-header {
            padding: 20px;
        }

        .page-title h1 {
            font-size: 22px;
        }

        .lands-comparison {
            grid-template-columns: 1fr;
        }

        .overlap-indicator {
            margin: 0 auto;
        }

        .alert-actions {
            flex-wrap: wrap;
        }

        .btn-investigate, .btn-resolve, .btn-dismiss {
            flex: 1;
            justify-content: center;
        }
    }
    </style>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        $('#resolveModal').on('show.bs.modal', function(e) {
            var alertId = $(e.relatedTarget).data('alertid');
            $('#resolveAlertId').val(alertId);
        });
    </script>
</body>
</html>
