<?php
/**
 * Edit User Details
 * Admin page to edit user details including region, district, village assignments
 */

define('APP_RUNNING', true);
session_start();
require_once '../db_connect.php';

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

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

// Get user ID
$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if(!$user_id) {
    header('Location: users');
    exit;
}

// Get user data
$user = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT u.*,
           r.name as region_name,
           d.name as district_name,
           v.name as village_name
    FROM users u
    LEFT JOIN regions r ON u.region_id = r.id
    LEFT JOIN districts d ON u.district_id = d.id
    LEFT JOIN villages v ON u.village_id = v.id
    WHERE u.id = $user_id
"));

if(!$user) {
    header('Location: users');
    exit;
}

// Get all regions
$regions = mysqli_query($conn, "SELECT id, name FROM regions ORDER BY name");

// Get districts if region is set
$districts = null;
if($user['region_id']) {
    $districts = mysqli_query($conn, "SELECT id, name FROM districts WHERE region_id = {$user['region_id']} ORDER BY name");
}

// Get villages if district is set
$villages = null;
if($user['district_id']) {
    $villages = mysqli_query($conn, "SELECT id, name FROM villages WHERE district_id = {$user['district_id']} ORDER BY name");
}

// Handle form submission
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $full_name = mysqli_real_escape_string($conn, trim($_POST['full_name']));
    $email = mysqli_real_escape_string($conn, trim($_POST['email']));
    $phone = mysqli_real_escape_string($conn, trim($_POST['phone']));
    $national_id = mysqli_real_escape_string($conn, trim($_POST['national_id']));
    $role = mysqli_real_escape_string($conn, $_POST['role']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    $region_id = intval($_POST['region_id'] ?? 0);
    $district_id = intval($_POST['district_id'] ?? 0);
    $village_id = intval($_POST['village_id'] ?? 0);

    // Validate role
    $valid_roles = ['user', 'broker', 'village_chairman', 'land_officer', 'surveyor', 'district_officer', 'land_council', 'user_admin'];
    if(!in_array($role, $valid_roles)) {
        $error = 'Invalid role selected';
    } else {
        // Check email uniqueness
        $email_check = mysqli_query($conn, "SELECT id FROM users WHERE email = '$email' AND id != $user_id");
        if(mysqli_num_rows($email_check) > 0) {
            $error = 'Email already in use by another user';
        } else {
            // Build update query
            $region_id_sql = $region_id > 0 ? $region_id : 'NULL';
            $district_id_sql = $district_id > 0 ? $district_id : 'NULL';
            $village_id_sql = $village_id > 0 ? $village_id : 'NULL';

            $sql = "UPDATE users SET
                full_name = '$full_name',
                email = '$email',
                phone = '$phone',
                national_id = '$national_id',
                role = '$role',
                status = '$status',
                region_id = $region_id_sql,
                district_id = $district_id_sql,
                village_id = $village_id_sql,
                updated_at = NOW()
                WHERE id = $user_id";

            if(mysqli_query($conn, $sql)) {
                // Log the action
                mysqli_query($conn, "INSERT INTO activity_logs (user_id, action, description, ip_address)
                    VALUES ($admin_id, 'edit_user', 'Updated user #$user_id details', '{$_SERVER['REMOTE_ADDR']}')");

                $message = 'User details updated successfully';

                // Refresh user data
                $user = mysqli_fetch_assoc(mysqli_query($conn, "
                    SELECT u.*, r.name as region_name, d.name as district_name, v.name as village_name
                    FROM users u
                    LEFT JOIN regions r ON u.region_id = r.id
                    LEFT JOIN districts d ON u.district_id = d.id
                    LEFT JOIN villages v ON u.village_id = v.id
                    WHERE u.id = $user_id
                "));

                // Refresh dropdowns
                if($user['region_id']) {
                    $districts = mysqli_query($conn, "SELECT id, name FROM districts WHERE region_id = {$user['region_id']} ORDER BY name");
                }
                if($user['district_id']) {
                    $villages = mysqli_query($conn, "SELECT id, name FROM villages WHERE district_id = {$user['district_id']} ORDER BY name");
                }
            } else {
                $error = 'Failed to update user: ' . mysqli_error($conn);
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit User - 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">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.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-user-edit"></i> Edit User</h1>
                    <p>Update user details and role assignments</p>
                </div>
                <div class="header-actions">
                    <a href="users" class="btn-back">
                        <i class="fas fa-arrow-left"></i> Back to Users
                    </a>
                </div>
            </div>
        </div>

        <?php if($message): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle"></i> <?php echo $message; ?>
        </div>
        <?php endif; ?>

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

        <div class="content-grid">
            <!-- User Info Card -->
            <div class="content-card user-overview">
                <div class="user-header">
                    <div class="user-avatar">
                        <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
                    </div>
                    <div class="user-info">
                        <h2><?php echo htmlspecialchars($user['full_name'] ?: $user['username']); ?></h2>
                        <p>@<?php echo $user['username']; ?></p>
                        <span class="role-badge role-<?php echo $user['role']; ?>">
                            <?php echo ucfirst(str_replace('_', ' ', $user['role'])); ?>
                        </span>
                    </div>
                </div>
                <div class="user-meta">
                    <div class="meta-item">
                        <i class="fas fa-calendar"></i>
                        <span>Joined <?php echo date('M d, Y', strtotime($user['created_at'])); ?></span>
                    </div>
                    <div class="meta-item">
                        <i class="fas fa-map-marker-alt"></i>
                        <span>
                            <?php
                            $location_parts = [];
                            if($user['village_name']) $location_parts[] = $user['village_name'];
                            if($user['district_name']) $location_parts[] = $user['district_name'];
                            if($user['region_name']) $location_parts[] = $user['region_name'];
                            echo !empty($location_parts) ? implode(', ', $location_parts) : 'No location assigned';
                            ?>
                        </span>
                    </div>
                </div>
            </div>

            <!-- Edit Form -->
            <div class="content-card">
                <div class="card-header-custom">
                    <h3><i class="fas fa-edit"></i> Edit Details</h3>
                </div>
                <div class="card-body">
                    <form method="POST" id="editUserForm">
                        <!-- Basic Information -->
                        <div class="form-section">
                            <h4><i class="fas fa-user"></i> Basic Information</h4>
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label>Full Name <span class="required">*</span></label>
                                    <input type="text" name="full_name" class="form-control"
                                           value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>Username</label>
                                    <input type="text" class="form-control" value="<?php echo $user['username']; ?>" disabled>
                                    <small class="text-muted">Username cannot be changed</small>
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label>Email <span class="required">*</span></label>
                                    <input type="email" name="email" class="form-control"
                                           value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>Phone</label>
                                    <input type="text" name="phone" class="form-control"
                                           value="<?php echo htmlspecialchars($user['phone']); ?>">
                                </div>
                            </div>
                            <div class="form-group">
                                <label>National ID (NIDA)</label>
                                <input type="text" name="national_id" class="form-control"
                                       value="<?php echo htmlspecialchars($user['national_id'] ?? ''); ?>"
                                       placeholder="Enter national ID number">
                            </div>
                        </div>

                        <!-- Role & Status -->
                        <div class="form-section">
                            <h4><i class="fas fa-user-tag"></i> Role & Status</h4>
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label>Role <span class="required">*</span></label>
                                    <select name="role" id="roleSelect" class="form-control" required>
                                        <optgroup label="Standard Roles">
                                            <option value="user" <?php echo $user['role'] == 'user' ? 'selected' : ''; ?>>Land Owner (User)</option>
                                            <option value="broker" <?php echo $user['role'] == 'broker' ? 'selected' : ''; ?>>Broker/Agent</option>
                                        </optgroup>
                                        <optgroup label="CBC Village Roles">
                                            <option value="village_chairman" <?php echo $user['role'] == 'village_chairman' ? 'selected' : ''; ?>>Village Chairman (Mwenyekiti)</option>
                                            <option value="land_officer" <?php echo $user['role'] == 'land_officer' ? 'selected' : ''; ?>>Land Officer (Afisa Ardhi)</option>
                                            <option value="land_council" <?php echo $user['role'] == 'land_council' ? 'selected' : ''; ?>>Land Council (Baraza la Ardhi)</option>
                                            <option value="surveyor" <?php echo $user['role'] == 'surveyor' ? 'selected' : ''; ?>>Surveyor (Mpima Ardhi)</option>
                                            <option value="district_officer" <?php echo $user['role'] == 'district_officer' ? 'selected' : ''; ?>>District Officer (Afisa Wilaya)</option>
                                        </optgroup>
                                        <optgroup label="Admin Roles">
                                            <option value="user_admin" <?php echo $user['role'] == 'user_admin' ? 'selected' : ''; ?>>Payment Admin</option>
                                        </optgroup>
                                    </select>
                                </div>
                                <div class="form-group col-md-6">
                                    <label>Status <span class="required">*</span></label>
                                    <select name="status" class="form-control" required>
                                        <option value="pending" <?php echo $user['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                        <option value="approved" <?php echo $user['status'] == 'approved' ? 'selected' : ''; ?>>Approved</option>
                                        <option value="rejected" <?php echo $user['status'] == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                        <option value="suspended" <?php echo $user['status'] == 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Location Assignment -->
                        <div class="form-section" id="locationSection">
                            <h4><i class="fas fa-map-marker-alt"></i> Location Assignment</h4>
                            <p class="section-note">
                                <i class="fas fa-info-circle"></i>
                                Assign location for CBC roles. Village officials will only see lands in their assigned village.
                            </p>
                            <div class="form-row">
                                <div class="form-group col-md-4">
                                    <label>Region</label>
                                    <select name="region_id" id="regionSelect" class="form-control">
                                        <option value="">Select Region</option>
                                        <?php
                                        mysqli_data_seek($regions, 0);
                                        while($region = mysqli_fetch_assoc($regions)):
                                        ?>
                                        <option value="<?php echo $region['id']; ?>" <?php echo $user['region_id'] == $region['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($region['name']); ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="form-group col-md-4">
                                    <label>District</label>
                                    <select name="district_id" id="districtSelect" class="form-control" <?php echo !$user['region_id'] ? 'disabled' : ''; ?>>
                                        <option value="">Select District</option>
                                        <?php if($districts): while($district = mysqli_fetch_assoc($districts)): ?>
                                        <option value="<?php echo $district['id']; ?>" <?php echo $user['district_id'] == $district['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($district['name']); ?>
                                        </option>
                                        <?php endwhile; endif; ?>
                                    </select>
                                </div>
                                <div class="form-group col-md-4">
                                    <label>Village</label>
                                    <select name="village_id" id="villageSelect" class="form-control" <?php echo !$user['district_id'] ? 'disabled' : ''; ?>>
                                        <option value="">Select Village</option>
                                        <?php if($villages): while($village = mysqli_fetch_assoc($villages)): ?>
                                        <option value="<?php echo $village['id']; ?>" <?php echo $user['village_id'] == $village['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($village['name']); ?>
                                        </option>
                                        <?php endwhile; endif; ?>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> Save Changes
                            </button>
                            <a href="users" class="btn btn-secondary">
                                <i class="fas fa-times"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </main>

    <style>
    .page-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 20px;
        padding: 30px;
        margin-bottom: 30px;
        color: white;
    }

    .page-header-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 20px;
    }

    .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;
    }

    .btn-back {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 12px 24px;
        background: rgba(255,255,255,0.2);
        color: white;
        border-radius: 12px;
        text-decoration: none;
        font-weight: 600;
        transition: all 0.3s;
    }

    .btn-back:hover {
        background: rgba(255,255,255,0.3);
        color: white;
        text-decoration: none;
    }

    .content-grid {
        display: grid;
        grid-template-columns: 300px 1fr;
        gap: 24px;
    }

    @media (max-width: 992px) {
        .content-grid {
            grid-template-columns: 1fr;
        }
    }

    .content-card {
        background: white;
        border-radius: 20px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.05);
        overflow: hidden;
    }

    .user-overview {
        padding: 30px;
        text-align: center;
    }

    .user-avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 40px;
        font-weight: 700;
        margin: 0 auto 20px;
    }

    .user-info h2 {
        font-size: 22px;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 4px;
    }

    .user-info p {
        color: #94a3b8;
        margin: 0 0 12px;
    }

    .role-badge {
        display: inline-block;
        padding: 6px 16px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    .role-user { background: #e2e8f0; color: #475569; }
    .role-broker { background: linear-gradient(135deg, #06b6d4, #0891b2); color: white; }
    .role-village_chairman { background: linear-gradient(135deg, #11998e, #38ef7d); color: white; }
    .role-land_officer { background: linear-gradient(135deg, #f093fb, #f5576c); color: white; }
    .role-land_council { background: linear-gradient(135deg, #4facfe, #00f2fe); color: white; }
    .role-surveyor { background: linear-gradient(135deg, #8b5cf6, #6366f1); color: white; }
    .role-district_officer { background: linear-gradient(135deg, #f59e0b, #d97706); color: white; }
    .role-user_admin { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }

    .user-meta {
        margin-top: 24px;
        padding-top: 24px;
        border-top: 1px solid #f1f5f9;
    }

    .meta-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 8px 0;
        color: #64748b;
        font-size: 14px;
    }

    .meta-item i {
        width: 20px;
        color: #94a3b8;
    }

    .card-header-custom {
        padding: 24px 30px;
        border-bottom: 1px solid #f1f5f9;
    }

    .card-header-custom h3 {
        font-size: 18px;
        font-weight: 600;
        margin: 0;
        color: #1e293b;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .card-body {
        padding: 30px;
    }

    .form-section {
        margin-bottom: 30px;
        padding-bottom: 30px;
        border-bottom: 1px solid #f1f5f9;
    }

    .form-section:last-of-type {
        border-bottom: none;
        margin-bottom: 0;
        padding-bottom: 0;
    }

    .form-section h4 {
        font-size: 16px;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 20px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .form-section h4 i {
        color: #667eea;
    }

    .section-note {
        background: #f8fafc;
        padding: 12px 16px;
        border-radius: 10px;
        font-size: 13px;
        color: #64748b;
        margin-bottom: 20px;
    }

    .section-note i {
        color: #667eea;
        margin-right: 8px;
    }

    .form-group label {
        font-weight: 500;
        color: #475569;
        margin-bottom: 8px;
    }

    .required {
        color: #ef4444;
    }

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

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

    .form-control:disabled {
        background: #f8fafc;
        cursor: not-allowed;
    }

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

    .btn {
        padding: 14px 28px;
        border-radius: 12px;
        font-weight: 600;
        font-size: 14px;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        transition: all 0.3s;
        border: none;
    }

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

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
    }

    .btn-secondary {
        background: #f1f5f9;
        color: #64748b;
    }

    .btn-secondary:hover {
        background: #e2e8f0;
        color: #475569;
        text-decoration: none;
    }

    .alert {
        border: none;
        border-radius: 14px;
        padding: 16px 20px;
        margin-bottom: 25px;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .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;
    }

    .alert-danger {
        background: linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(220, 38, 38, 0.1) 100%);
        color: #991b1b;
        border-left: 4px solid #ef4444;
    }

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

        .page-header-content {
            flex-direction: column;
            align-items: flex-start;
        }

        .card-body {
            padding: 20px;
        }

        .form-actions {
            flex-direction: column;
        }

        .btn {
            width: 100%;
            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 src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function() {
            // Initialize Select2
            $('#regionSelect, #districtSelect, #villageSelect').select2({
                theme: 'bootstrap-5',
                allowClear: true
            });

            // Region change - load districts
            $('#regionSelect').on('change', function() {
                const regionId = $(this).val();
                const $district = $('#districtSelect');
                const $village = $('#villageSelect');

                $district.prop('disabled', true).html('<option value="">Loading...</option>');
                $village.prop('disabled', true).html('<option value="">Select District first</option>');

                if (regionId) {
                    fetch('../api/get_locations.php?action=districts&region_id=' + regionId)
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                let options = '<option value="">Select District</option>';
                                data.data.forEach(d => {
                                    options += `<option value="${d.id}">${d.name}</option>`;
                                });
                                $district.html(options).prop('disabled', false);
                            }
                        });
                }
            });

            // District change - load villages
            $('#districtSelect').on('change', function() {
                const districtId = $(this).val();
                const $village = $('#villageSelect');

                $village.prop('disabled', true).html('<option value="">Loading...</option>');

                if (districtId) {
                    fetch('../api/get_locations.php?action=villages&district_id=' + districtId)
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                let options = '<option value="">Select Village</option>';
                                data.data.forEach(v => {
                                    options += `<option value="${v.id}">${v.name}</option>`;
                                });
                                $village.html(options).prop('disabled', false);
                            }
                        });
                }
            });

            // Show/hide location section based on role
            function toggleLocationSection() {
                const role = $('#roleSelect').val();
                const cbcRoles = ['village_chairman', 'land_officer', 'land_council', 'surveyor', 'district_officer'];

                if (cbcRoles.includes(role)) {
                    $('#locationSection').show();
                } else {
                    $('#locationSection').hide();
                }
            }

            $('#roleSelect').on('change', toggleLocationSection);
            toggleLocationSection();
        });
    </script>
</body>
</html>
