<?php
/**
 * Land Dispute Reporting Page
 * Allows anyone to report a land dispute
 * Works with or without login
 */

session_start();
require_once 'db_connect.php';

$message = '';
$error = '';
$land_id = isset($_GET['land_id']) ? (int)$_GET['land_id'] : 0;

// Get land info if land_id provided
$land = null;
if($land_id) {
    $result = mysqli_query($conn, "
        SELECT l.*, u.full_name as owner_name, u.phone as owner_phone,
               v.name as village_name, d.name as district_name
        FROM lands l
        JOIN users u ON l.user_id = u.id
        LEFT JOIN villages v ON l.village_id = v.id
        LEFT JOIN districts d ON l.district_id = d.id
        WHERE l.id = $land_id
    ");
    $land = mysqli_fetch_assoc($result);
}

// Handle form submission
if($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect form data
    $selected_land_id = isset($_POST['land_id']) ? (int)$_POST['land_id'] : $land_id;
    $dispute_type = mysqli_real_escape_string($conn, $_POST['dispute_type'] ?? '');
    $description = mysqli_real_escape_string($conn, $_POST['description'] ?? '');
    $reporter_name = mysqli_real_escape_string($conn, $_POST['reporter_name'] ?? '');
    $reporter_phone = mysqli_real_escape_string($conn, $_POST['reporter_phone'] ?? '');
    $reporter_national_id = mysqli_real_escape_string($conn, $_POST['reporter_national_id'] ?? '');
    $reporter_user_id = $_SESSION['user_id'] ?? 'NULL';

    // Validate
    $errors = [];
    if(empty($selected_land_id)) $errors[] = "Please select a land to report";
    if(empty($dispute_type)) $errors[] = "Please select dispute type";
    if(empty($description)) $errors[] = "Please describe the dispute";
    if(empty($reporter_name)) $errors[] = "Please enter your name";
    if(empty($reporter_phone)) $errors[] = "Please enter your phone number";

    // Get land details for the selected land
    if($selected_land_id) {
        $result = mysqli_query($conn, "
            SELECT l.*, v.id as village_id, d.id as district_id
            FROM lands l
            LEFT JOIN villages v ON l.village_id = v.id
            LEFT JOIN districts d ON l.district_id = d.id
            WHERE l.id = $selected_land_id
        ");
        $selected_land = mysqli_fetch_assoc($result);

        if(!$selected_land) {
            $errors[] = "Selected land not found";
        }
    }

    if(empty($errors)) {
        // Generate dispute number
        $year = date('Y');
        $count_result = mysqli_query($conn, "SELECT COUNT(*) + 1 as num FROM land_disputes WHERE YEAR(created_at) = $year");
        $count = mysqli_fetch_assoc($count_result)['num'];
        $dispute_number = "DSP-$year-" . str_pad($count, 5, '0', STR_PAD_LEFT);

        // Insert dispute
        $village_id = $selected_land['village_id'] ?? 'NULL';
        $district_id = $selected_land['district_id'] ?? 'NULL';
        $land_owner_id = $selected_land['user_id'];

        $sql = "INSERT INTO land_disputes (
                    dispute_number, land_id, land_owner_id,
                    reported_by_user_id, reported_by_name, reported_by_phone, reported_by_national_id,
                    dispute_type, dispute_description,
                    village_id, district_id, status, priority
                ) VALUES (
                    '$dispute_number', $selected_land_id, $land_owner_id,
                    " . ($reporter_user_id !== 'NULL' ? $reporter_user_id : 'NULL') . ",
                    '$reporter_name', '$reporter_phone', " . ($reporter_national_id ? "'$reporter_national_id'" : 'NULL') . ",
                    '$dispute_type', '$description',
                    " . ($village_id !== 'NULL' ? $village_id : 'NULL') . ",
                    " . ($district_id !== 'NULL' ? $district_id : 'NULL') . ",
                    'reported', 'medium'
                )";

        if(mysqli_query($conn, $sql)) {
            $dispute_id = mysqli_insert_id($conn);

            // Log activity
            mysqli_query($conn, "
                INSERT INTO dispute_activities (dispute_id, activity_type, description, performed_by)
                VALUES ($dispute_id, 'created', 'Dispute reported by $reporter_name ($reporter_phone)', " . ($reporter_user_id !== 'NULL' ? $reporter_user_id : 'NULL') . ")
            ");

            // Update land status to disputed
            mysqli_query($conn, "UPDATE lands SET status = 'disputed' WHERE id = $selected_land_id");

            // Log in land history
            mysqli_query($conn, "
                INSERT INTO land_history (land_id, event_type, event_description, performed_by)
                VALUES ($selected_land_id, 'dispute_raised', 'Dispute #$dispute_number reported: $dispute_type', " . ($reporter_user_id !== 'NULL' ? $reporter_user_id : 'NULL') . ")
            ");

            // Notify land owner
            $title = mysqli_real_escape_string($conn, "Dispute Reported - Mgogoro Umeandikwa");
            $msg = mysqli_real_escape_string($conn, "A dispute has been reported on your land. Dispute #: $dispute_number");
            mysqli_query($conn, "
                INSERT INTO cbc_notifications (user_id, notification_type, title, message, land_id, dispute_id)
                VALUES ($land_owner_id, 'dispute_raised', '$title', '$msg', $selected_land_id, $dispute_id)
            ");

            $message = "Dispute reported successfully! Reference Number: <strong>$dispute_number</strong>. Please save this number for tracking.";
        } else {
            $error = "Failed to submit dispute: " . mysqli_error($conn);
        }
    } else {
        $error = implode('<br>', $errors);
    }
}

// Get recent lands for search (if no land_id provided)
$recent_lands = [];
if(!$land_id) {
    $result = mysqli_query($conn, "
        SELECT l.id, l.land_name, u.full_name as owner_name, v.name as village_name
        FROM lands l
        JOIN users u ON l.user_id = u.id
        LEFT JOIN villages v ON l.village_id = v.id
        ORDER BY l.created_at DESC
        LIMIT 20
    ");
    while($row = mysqli_fetch_assoc($result)) {
        $recent_lands[] = $row;
    }
}

// Dispute types
$dispute_types = [
    'boundary_overlap' => 'Boundary Overlap - Mpaka unaingilia',
    'ownership_claim' => 'Ownership Claim - Madai ya umiliki',
    'illegal_occupation' => 'Illegal Occupation - Uvamizi wa ardhi',
    'inheritance_dispute' => 'Inheritance Dispute - Mgogoro wa urithi',
    'sale_fraud' => 'Sale Fraud - Ulaghai wa mauzo',
    'double_registration' => 'Double Registration - Usajili mara mbili',
    'encroachment' => 'Encroachment - Uvamizi wa sehemu',
    'other' => 'Other - Mengineyo'
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Report Land Dispute - Land Secure</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&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">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            padding: 40px 20px;
        }

        .container {
            max-width: 800px;
        }

        .page-header {
            text-align: center;
            margin-bottom: 40px;
        }

        .page-header .logo {
            display: inline-flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 20px;
        }

        .page-header .logo-icon {
            width: 56px;
            height: 56px;
            background: linear-gradient(135deg, #f5af19 0%, #f12711 100%);
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
            box-shadow: 0 8px 20px rgba(241, 39, 17, 0.3);
        }

        .page-header h1 {
            font-size: 28px;
            font-weight: 700;
            color: #1a1d21;
            margin: 0;
        }

        .page-header p {
            color: #6c757d;
            margin-top: 8px;
        }

        .dispute-form {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }

        .form-section {
            margin-bottom: 30px;
        }

        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #1a1d21;
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-title i {
            color: #f12711;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            color: #1a1d21;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .form-control {
            border: 2px solid #e9ecef;
            border-radius: 12px;
            padding: 14px 16px;
            font-size: 15px;
            transition: all 0.3s;
        }

        .form-control:focus {
            border-color: #f5af19;
            box-shadow: 0 0 0 4px rgba(245, 175, 25, 0.1);
        }

        textarea.form-control {
            min-height: 120px;
            resize: vertical;
        }

        .land-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            border: 2px solid #e9ecef;
        }

        .land-card .land-name {
            font-weight: 600;
            color: #1a1d21;
            font-size: 18px;
        }

        .land-card .land-meta {
            color: #6c757d;
            font-size: 14px;
            margin-top: 8px;
        }

        .dispute-type-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 12px;
        }

        .dispute-type-option {
            position: relative;
        }

        .dispute-type-option input {
            position: absolute;
            opacity: 0;
        }

        .dispute-type-option label {
            display: block;
            padding: 14px 16px;
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 500;
            font-size: 13px;
        }

        .dispute-type-option input:checked + label {
            background: #fff3cd;
            border-color: #f5af19;
            color: #856404;
        }

        .dispute-type-option label:hover {
            border-color: #f5af19;
        }

        .btn-submit {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            width: 100%;
            padding: 16px;
            background: linear-gradient(135deg, #f5af19 0%, #f12711 100%);
            border: none;
            border-radius: 12px;
            color: white;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-submit:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 30px rgba(241, 39, 17, 0.3);
        }

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

        .alert-success {
            background: #d4edda;
            color: #155724;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
        }

        .success-card {
            text-align: center;
            padding: 40px;
        }

        .success-card .icon {
            width: 80px;
            height: 80px;
            background: #d4edda;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 24px;
        }

        .success-card .icon i {
            font-size: 40px;
            color: #155724;
        }

        .success-card h2 {
            color: #155724;
            margin-bottom: 16px;
        }

        .reference-number {
            display: inline-block;
            background: #155724;
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 20px;
            font-weight: 700;
            letter-spacing: 1px;
            margin: 16px 0;
        }

        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: #6c757d;
            text-decoration: none;
            margin-bottom: 24px;
            font-weight: 500;
        }

        .back-link:hover {
            color: #1a1d21;
        }

        .search-land {
            position: relative;
        }

        .search-land input {
            padding-left: 45px;
        }

        .search-land i {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
        }

        .land-results {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #e9ecef;
            border-radius: 12px;
            margin-top: 8px;
        }

        .land-result-item {
            padding: 12px 16px;
            border-bottom: 1px solid #e9ecef;
            cursor: pointer;
            transition: background 0.2s;
        }

        .land-result-item:hover {
            background: #f8f9fa;
        }

        .land-result-item:last-child {
            border-bottom: none;
        }

        @media (max-width: 768px) {
            .dispute-form {
                padding: 24px;
            }

            .dispute-type-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="<?php echo isset($_SESSION['user_id']) ? 'dashboard' : '/'; ?>" class="back-link">
            <i class="fas fa-arrow-left"></i> Back
        </a>

        <div class="page-header">
            <div class="logo">
                <div class="logo-icon">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <h1>Land Secure</h1>
            </div>
            <h1>Report Land Dispute</h1>
            <p>Ripoti Mgogoro wa Ardhi</p>
        </div>

        <?php if($message && strpos($message, 'successfully') !== false): ?>
        <div class="dispute-form">
            <div class="success-card">
                <div class="icon">
                    <i class="fas fa-check"></i>
                </div>
                <h2>Dispute Reported Successfully!</h2>
                <p>Your dispute has been submitted and will be reviewed by the village authority.</p>
                <p><strong>Your Reference Number:</strong></p>
                <div class="reference-number">
                    <?php
                    preg_match('/DSP-\d+-\d+/', $message, $matches);
                    echo $matches[0] ?? 'N/A';
                    ?>
                </div>
                <p class="text-muted">Please save this number to track your dispute status.</p>
                <a href="<?php echo isset($_SESSION['user_id']) ? 'dashboard' : '/'; ?>" class="btn btn-primary mt-4">
                    <i class="fas fa-home"></i> Return Home
                </a>
            </div>
        </div>
        <?php else: ?>

        <?php if($error): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle mr-2"></i> <?php echo $error; ?>
        </div>
        <?php endif; ?>

        <div class="dispute-form">
            <form method="POST">
                <!-- Land Selection -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-map-marked-alt"></i>
                        Land Information / Taarifa za Ardhi
                    </h3>

                    <?php if($land): ?>
                    <div class="land-card">
                        <input type="hidden" name="land_id" value="<?php echo $land['id']; ?>">
                        <div class="land-name">
                            <i class="fas fa-map mr-2"></i>
                            <?php echo htmlspecialchars($land['land_name']); ?>
                        </div>
                        <div class="land-meta">
                            <i class="fas fa-user"></i> Owner: <?php echo htmlspecialchars($land['owner_name']); ?><br>
                            <i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($land['village_name'] ?? 'N/A'); ?>,
                            <?php echo htmlspecialchars($land['district_name'] ?? 'N/A'); ?>
                        </div>
                    </div>
                    <?php else: ?>
                    <div class="form-group">
                        <label>Search Land / Tafuta Ardhi *</label>
                        <div class="search-land">
                            <i class="fas fa-search"></i>
                            <input type="text" class="form-control" id="landSearch"
                                   placeholder="Enter land name or owner name..." autocomplete="off">
                        </div>
                        <input type="hidden" name="land_id" id="selectedLandId" required>
                        <div class="land-results" id="landResults" style="display: none;"></div>
                        <div id="selectedLandCard" style="display: none; margin-top: 12px;"></div>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Dispute Type -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-exclamation-circle"></i>
                        Dispute Type / Aina ya Mgogoro *
                    </h3>

                    <div class="dispute-type-grid">
                        <?php foreach($dispute_types as $value => $label): ?>
                        <div class="dispute-type-option">
                            <input type="radio" name="dispute_type" value="<?php echo $value; ?>"
                                   id="type_<?php echo $value; ?>" required>
                            <label for="type_<?php echo $value; ?>"><?php echo $label; ?></label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Description -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-align-left"></i>
                        Dispute Description / Maelezo ya Mgogoro *
                    </h3>

                    <div class="form-group">
                        <textarea name="description" class="form-control" required
                                  placeholder="Please describe the dispute in detail. Include any relevant information such as:
- When did this issue start?
- What is the nature of the conflict?
- Have there been any attempts to resolve it?
- Who are the parties involved?"></textarea>
                    </div>
                </div>

                <!-- Reporter Info -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="fas fa-user"></i>
                        Your Information / Taarifa Zako *
                    </h3>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Full Name / Jina Kamili *</label>
                                <input type="text" name="reporter_name" class="form-control" required
                                       value="<?php echo htmlspecialchars($_SESSION['full_name'] ?? ''); ?>"
                                       placeholder="Enter your full name">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Phone Number / Nambari ya Simu *</label>
                                <input type="tel" name="reporter_phone" class="form-control" required
                                       value="<?php echo htmlspecialchars($_SESSION['phone'] ?? ''); ?>"
                                       placeholder="e.g., 0712345678">
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>National ID Number / Nambari ya Kitambulisho (Optional)</label>
                        <input type="text" name="reporter_national_id" class="form-control"
                               placeholder="Enter your national ID number">
                        <small class="form-text text-muted">
                            Providing your ID helps verify your identity and speeds up the process.
                        </small>
                    </div>
                </div>

                <button type="submit" class="btn-submit">
                    <i class="fas fa-paper-plane"></i>
                    Submit Dispute Report / Wasilisha Ripoti
                </button>

                <p class="text-center text-muted mt-3">
                    <i class="fas fa-info-circle"></i>
                    Your dispute will be reviewed by the village land authority.
                </p>
            </form>
        </div>
        <?php endif; ?>
    </div>

    <script src="assets/vendor/jquery/jquery.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        // Land search functionality
        var recentLands = <?php echo json_encode($recent_lands); ?>;

        $('#landSearch').on('focus', function() {
            showLandResults(recentLands);
        });

        $('#landSearch').on('input', function() {
            var query = $(this).val().toLowerCase();
            if (query.length < 2) {
                showLandResults(recentLands);
                return;
            }

            var filtered = recentLands.filter(function(land) {
                return land.land_name.toLowerCase().includes(query) ||
                       land.owner_name.toLowerCase().includes(query) ||
                       (land.village_name && land.village_name.toLowerCase().includes(query));
            });

            showLandResults(filtered);
        });

        function showLandResults(lands) {
            var $results = $('#landResults');
            $results.empty();

            if (lands.length === 0) {
                $results.html('<div class="land-result-item text-muted">No lands found</div>');
            } else {
                lands.forEach(function(land) {
                    $results.append(
                        '<div class="land-result-item" data-id="' + land.id + '" ' +
                        'data-name="' + land.land_name + '" ' +
                        'data-owner="' + land.owner_name + '" ' +
                        'data-village="' + (land.village_name || 'N/A') + '">' +
                        '<strong>' + land.land_name + '</strong><br>' +
                        '<small class="text-muted">Owner: ' + land.owner_name +
                        (land.village_name ? ' | ' + land.village_name : '') + '</small>' +
                        '</div>'
                    );
                });
            }

            $results.show();
        }

        $(document).on('click', '.land-result-item', function() {
            var id = $(this).data('id');
            var name = $(this).data('name');
            var owner = $(this).data('owner');
            var village = $(this).data('village');

            $('#selectedLandId').val(id);
            $('#landSearch').val(name);
            $('#landResults').hide();

            $('#selectedLandCard').html(
                '<div class="land-card">' +
                '<div class="land-name"><i class="fas fa-check-circle text-success mr-2"></i>' + name + '</div>' +
                '<div class="land-meta">' +
                '<i class="fas fa-user"></i> Owner: ' + owner + '<br>' +
                '<i class="fas fa-map-marker-alt"></i> ' + village +
                '</div></div>'
            ).show();
        });

        $(document).on('click', function(e) {
            if (!$(e.target).closest('.search-land').length) {
                $('#landResults').hide();
            }
        });
    </script>
</body>
</html>
