<?php
/**
 * Admin - Add User
 * Create users with any role including CBC village roles
 * Now includes location (region, district, village) and national ID
 */

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

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

$error = '';
$success = '';

// Get regions for dropdown
$regions = [];
$regions_result = mysqli_query($conn, "SELECT id, name FROM regions ORDER BY name");
if($regions_result) {
    while($row = mysqli_fetch_assoc($regions_result)) {
        $regions[] = $row;
    }
}

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $full_name = trim($_POST['full_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $national_id = trim($_POST['national_id'] ?? '');
    $role = $_POST['role'] ?? 'user';
    $status = $_POST['status'] ?? 'approved';

    // Location fields
    $region_id = !empty($_POST['region_id']) ? (int)$_POST['region_id'] : null;
    $district_id = !empty($_POST['district_id']) ? (int)$_POST['district_id'] : null;
    $village_id = !empty($_POST['village_id']) ? (int)$_POST['village_id'] : null;
    $village_name_new = trim($_POST['village_name_new'] ?? '');

    // Validate role
    $allowed_roles = ['admin', 'user_admin', 'user', 'broker', 'village_chairman', 'land_officer', 'surveyor', 'district_officer', 'land_council'];
    if(!in_array($role, $allowed_roles)) {
        $role = 'user';
    }

    // Validate status
    $allowed_statuses = ['approved', 'pending', 'suspended'];
    if(!in_array($status, $allowed_statuses)) {
        $status = 'approved';
    }

    // CBC roles that require location
    $cbc_roles = ['village_chairman', 'land_officer', 'surveyor', 'district_officer', 'land_council'];

    // Validation
    if(strlen($username) < 3) {
        $error = 'Username must be at least 3 characters';
    } elseif(!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
        $error = 'Username can only contain letters, numbers, and underscores';
    } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address';
    } elseif(strlen($password) < 6) {
        $error = 'Password must be at least 6 characters';
    } elseif(empty($full_name)) {
        $error = 'Full name is required';
    } elseif(in_array($role, $cbc_roles) && empty($region_id)) {
        $error = 'Region is required for CBC/Village roles';
    } elseif(in_array($role, $cbc_roles) && $role !== 'district_officer' && empty($district_id)) {
        $error = 'District is required for this role';
    } else {
        // Check if username exists
        $check = mysqli_query($conn, "SELECT id FROM users WHERE username = '" . mysqli_real_escape_string($conn, $username) . "'");
        if(mysqli_num_rows($check) > 0) {
            $error = 'Username already exists';
        } else {
            // Check if email exists
            $check = mysqli_query($conn, "SELECT id FROM users WHERE email = '" . mysqli_real_escape_string($conn, $email) . "'");
            if(mysqli_num_rows($check) > 0) {
                $error = 'Email already registered';
            } else {
                // Create new village if needed
                if(!empty($village_name_new) && $district_id) {
                    $village_name_esc = mysqli_real_escape_string($conn, $village_name_new);
                    $admin_id = $_SESSION['user_id'];
                    mysqli_query($conn, "INSERT INTO villages (district_id, name, added_by) VALUES ($district_id, '$village_name_esc', $admin_id)");
                    $village_id = mysqli_insert_id($conn);
                }

                // Hash password
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);

                // Generate broker code if role is broker
                $broker_code = null;
                if($role == 'broker') {
                    do {
                        $broker_code = str_pad(mt_rand(100000, 999999), 6, '0', STR_PAD_LEFT);
                        $code_check = mysqli_query($conn, "SELECT id FROM users WHERE broker_code = '$broker_code'");
                    } while(mysqli_num_rows($code_check) > 0);
                }

                $subscription_date = date('Y-m-d');
                $national_id_esc = mysqli_real_escape_string($conn, $national_id);

                // Build insert query with location fields
                $sql = "INSERT INTO users (username, email, password, full_name, phone, national_id, role, status, broker_code, subscription_start_date, region_id, district_id, village_id, created_at)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";

                $stmt = $conn->prepare($sql);
                $stmt->bind_param("sssssssssssss",
                    $username, $email, $hashed_password, $full_name, $phone, $national_id,
                    $role, $status, $broker_code, $subscription_date,
                    $region_id, $district_id, $village_id
                );

                if($stmt->execute()) {
                    $new_user_id = $stmt->insert_id;

                    // If CBC role, also insert into village_leaders table
                    if(in_array($role, ['village_chairman', 'land_officer', 'land_council']) && $village_id) {
                        $position = $role === 'village_chairman' ? 'chairman' : ($role === 'land_council' ? 'land_committee_member' : 'executive_officer');
                        $position_title = $role === 'village_chairman' ? 'Mwenyekiti' : ($role === 'land_council' ? 'Mjumbe wa Baraza la Ardhi' : 'Afisa Ardhi');
                        $today = date('Y-m-d');
                        $admin_id = $_SESSION['user_id'];

                        mysqli_query($conn, "INSERT INTO village_leaders (user_id, village_id, position, position_title, appointment_date, verified_by, verified_at)
                                            VALUES ($new_user_id, $village_id, '$position', '$position_title', '$today', $admin_id, NOW())");
                    }

                    // If surveyor, also insert into registered_surveyors table
                    if($role === 'surveyor') {
                        $license_number = 'LS-' . date('Y') . '-' . str_pad($new_user_id, 5, '0', STR_PAD_LEFT);
                        $admin_id = $_SESSION['user_id'];
                        $expiry_date = date('Y-m-d', strtotime('+2 years'));

                        mysqli_query($conn, "INSERT INTO registered_surveyors (user_id, license_number, license_type, license_expiry_date, verified_by, verified_at)
                                            VALUES ($new_user_id, '$license_number', 'licensed', '$expiry_date', $admin_id, NOW())");
                    }

                    // Log activity
                    $admin_id = $_SESSION['user_id'];
                    $log_desc = "Admin created new user: $username (Role: $role)";
                    mysqli_query($conn, "INSERT INTO activity_logs (user_id, action, description, ip_address) VALUES ($admin_id, 'user_created', '$log_desc', '{$_SERVER['REMOTE_ADDR']}')");

                    $success = "User '$username' created successfully!";
                    if($broker_code) {
                        $success .= " Broker code: $broker_code";
                    }

                    // Clear form
                    $username = $email = $full_name = $phone = $national_id = '';
                    $region_id = $district_id = $village_id = null;
                } else {
                    $error = 'Failed to create 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>Add 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">
    <style>
        :root {
            --primary: #4f46e5;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
            --village-color: #11998e;
        }
        body { font-family: 'Inter', sans-serif; background: #f1f5f9; min-height: 100vh; }
        .main-content { margin-left: 280px; padding: 24px; padding-bottom: 100px; overflow: visible; }
        @media (max-width: 1024px) { .main-content { margin-left: 0; padding-top: 90px; } }

        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 16px;
            padding: 30px;
            margin-bottom: 24px;
            color: white;
        }
        .page-header h1 { font-size: 24px; font-weight: 700; margin: 0 0 8px; }
        .page-header p { margin: 0; opacity: 0.9; }

        .form-card {
            background: white;
            border-radius: 16px;
            padding: 32px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            max-width: 800px;
            overflow: visible;
            margin-bottom: 50px;
        }

        .form-section {
            margin-bottom: 28px;
            padding-bottom: 24px;
            border-bottom: 1px solid #e2e8f0;
        }
        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        .section-title {
            font-size: 16px;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .section-title i {
            color: var(--primary);
        }
        .section-title.village-section i {
            color: var(--village-color);
        }

        .form-group { margin-bottom: 20px; }
        .form-label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: #334155;
            margin-bottom: 8px;
        }
        .form-control {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.2s;
        }
        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        .role-options {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
        }
        .role-option {
            position: relative;
        }
        .role-option input {
            position: absolute;
            opacity: 0;
        }
        .role-option label {
            display: block;
            padding: 16px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.2s;
        }
        .role-option input:checked + label {
            border-color: var(--primary);
            background: rgba(79, 70, 229, 0.05);
        }
        .role-option.village-role input:checked + label {
            border-color: var(--village-color);
            background: rgba(17, 153, 142, 0.05);
        }
        .role-option label h4 {
            font-size: 14px;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 4px;
        }
        .role-option label p {
            font-size: 12px;
            color: #64748b;
            margin: 0;
        }
        .role-option label i {
            font-size: 24px;
            color: var(--primary);
            margin-bottom: 8px;
        }
        .role-option.village-role label i {
            color: var(--village-color);
        }


        .btn {
            padding: 12px 24px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 600;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
        }
        .btn-primary {
            background: var(--primary);
            color: white;
        }
        .btn-primary:hover {
            background: #4338ca;
            transform: translateY(-1px);
        }
        .btn-outline {
            background: white;
            border: 2px solid #e2e8f0;
            color: #64748b;
        }
        .btn-outline:hover {
            background: #f8fafc;
        }

        .alert {
            padding: 14px 18px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .alert-success { background: #d4edda; color: #155724; }
        .alert-danger { background: #f8d7da; color: #721c24; }

        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: #64748b;
            text-decoration: none;
            font-size: 14px;
            margin-bottom: 16px;
        }
        .back-link:hover { color: var(--primary); }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }
        .form-row-3 {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
        }
        @media (max-width: 992px) {
            .form-row-3 { grid-template-columns: 1fr 1fr; }
        }
        @media (max-width: 768px) {
            .form-row, .form-row-3 { grid-template-columns: 1fr; }
            .role-options { grid-template-columns: 1fr; }
        }

        select.form-control {
            width: 100%;
            min-width: 0;
            appearance: auto;
            -webkit-appearance: menulist;
            -moz-appearance: menulist;
            cursor: pointer;
            background-color: white;
        }

        select.form-control:disabled {
            background-color: #f1f5f9;
            cursor: not-allowed;
        }

        /* Ensure form sections have enough space */
        .form-section {
            position: relative;
            z-index: 1;
        }

    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <div class="main-content">
        <a href="users" class="back-link">
            <i class="fas fa-arrow-left"></i> Back to Users
        </a>

        <div class="page-header">
            <h1><i class="fas fa-user-plus"></i> Add New User</h1>
            <p>Create a new user account with any role including CBC village roles</p>
        </div>

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

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

        <div class="form-card">
            <form method="POST" id="addUserForm">
                <!-- Basic Information -->
                <div class="form-section">
                    <h3 class="section-title"><i class="fas fa-user"></i> Basic Information</h3>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Username *</label>
                            <input type="text" name="username" class="form-control" value="<?php echo htmlspecialchars($username ?? ''); ?>" required placeholder="Enter username">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Email *</label>
                            <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($email ?? ''); ?>" required placeholder="Enter email">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Full Name *</label>
                            <input type="text" name="full_name" class="form-control" value="<?php echo htmlspecialchars($full_name ?? ''); ?>" required placeholder="Enter full name">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Phone</label>
                            <input type="text" name="phone" class="form-control" value="<?php echo htmlspecialchars($phone ?? ''); ?>" placeholder="e.g., 0712345678">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">National ID (NIDA) </label>
                            <input type="text" name="national_id" class="form-control" value="<?php echo htmlspecialchars($national_id ?? ''); ?>" placeholder="Enter National ID number">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Password *</label>
                            <input type="password" name="password" class="form-control" required placeholder="Min 6 characters">
                        </div>
                    </div>
                </div>

                <!-- Role Selection -->
                <div class="form-section">
                    <h3 class="section-title"><i class="fas fa-user-tag"></i> Select Role</h3>

                    <p style="color: #64748b; font-size: 13px; margin-bottom: 16px;">Standard Roles</p>
                    <div class="role-options">
                        <div class="role-option">
                            <input type="radio" name="role" value="user" id="role_user" checked>
                            <label for="role_user">
                                <i class="fas fa-user"></i>
                                <h4>Regular User</h4>
                                <p>Can add and manage their own lands</p>
                            </label>
                        </div>
                        <div class="role-option">
                            <input type="radio" name="role" value="broker" id="role_broker">
                            <label for="role_broker">
                                <i class="fas fa-handshake"></i>
                                <h4>Broker</h4>
                                <p>Can manage lands for their clients</p>
                            </label>
                        </div>
                        <div class="role-option">
                            <input type="radio" name="role" value="user_admin" id="role_user_admin">
                            <label for="role_user_admin">
                                <i class="fas fa-user-shield"></i>
                                <h4>Payment Admin</h4>
                                <p>Can only confirm payments</p>
                            </label>
                        </div>
                        <div class="role-option">
                            <input type="radio" name="role" value="admin" id="role_admin">
                            <label for="role_admin">
                                <i class="fas fa-crown"></i>
                                <h4>Full Admin</h4>
                                <p>Full access to all features</p>
                            </label>
                        </div>
                    </div>
                </div>

                <!-- CBC Village Roles -->
                <div class="form-section">
                    <h3 class="section-title village-section"><i class="fas fa-landmark"></i> CBC Village Roles</h3>
                    <p style="color: #64748b; font-size: 13px; margin-bottom: 16px;">For village land verification system</p>

                    <div class="role-options">
                        <div class="role-option village-role">
                            <input type="radio" name="role" value="village_chairman" id="role_chairman" class="cbc-role">
                            <label for="role_chairman">
                                <i class="fas fa-landmark"></i>
                                <h4>Village Chairman</h4>
                                <p>Mwenyekiti - Approve land registrations</p>
                            </label>
                        </div>
                        <div class="role-option village-role">
                            <input type="radio" name="role" value="land_council" id="role_land_council" class="cbc-role">
                            <label for="role_land_council">
                                <i class="fas fa-users"></i>
                                <h4>Mjumbe Baraza la Ardhi</h4>
                                <p>Kijiji/Mtaa - Land Council Member</p>
                            </label>
                        </div>
                        <div class="role-option village-role">
                            <input type="radio" name="role" value="land_officer" id="role_land_officer" class="cbc-role">
                            <label for="role_land_officer">
                                <i class="fas fa-map-marked-alt"></i>
                                <h4>Land Officer</h4>
                                <p>Afisa Ardhi - Manage village land records</p>
                            </label>
                        </div>
                        <div class="role-option village-role">
                            <input type="radio" name="role" value="surveyor" id="role_surveyor" class="cbc-role">
                            <label for="role_surveyor">
                                <i class="fas fa-ruler-combined"></i>
                                <h4>Surveyor</h4>
                                <p>Mpima Ardhi - Professional land verification</p>
                            </label>
                        </div>
                        <div class="role-option village-role">
                            <input type="radio" name="role" value="district_officer" id="role_district" class="cbc-role">
                            <label for="role_district">
                                <i class="fas fa-city"></i>
                                <h4>District Officer</h4>
                                <p>Afisa Wilaya - District-level oversight</p>
                            </label>
                        </div>
                    </div>

                </div>

                <!-- Location Section - Always visible -->
                <div class="form-section">
                    <h3 class="section-title"><i class="fas fa-map-marker-alt"></i> Location / Mahali</h3>
                    <p style="color: #64748b; font-size: 13px; margin-bottom: 16px;">Required for CBC roles, optional for other users</p>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Region / Mkoa</label>
                            <select name="region_id" id="regionSelect" class="form-control" style="width: 100%;">
                                <option value="">-- Select Region --</option>
                                <?php if(empty($regions)): ?>
                                <option value="" disabled style="color: red;">No regions found - Run tanzania_locations.sql</option>
                                <?php else: ?>
                                <?php foreach($regions as $region): ?>
                                <option value="<?php echo $region['id']; ?>"><?php echo htmlspecialchars($region['name']); ?></option>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">District / Wilaya</label>
                            <select name="district_id" id="districtSelect" class="form-control" style="width: 100%;" disabled>
                                <option value="">-- Select District --</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Village/Street / Kijiji/Mtaa</label>
                            <select name="village_id" id="villageSelect" class="form-control" style="width: 100%;" disabled>
                                <option value="">-- Select Village --</option>
                                <option value="new">+ Add New Village</option>
                            </select>
                        </div>
                        <div class="form-group" id="newVillageInput" style="display: none;">
                            <label class="form-label">New Village/Street Name</label>
                            <input type="text" name="village_name_new" class="form-control" placeholder="Enter new village or street name">
                        </div>
                    </div>
                </div>

                <!-- Account Status -->
                <div class="form-section">
                    <h3 class="section-title"><i class="fas fa-toggle-on"></i> Account Status</h3>

                    <div class="form-group">
                        <select name="status" class="form-control" style="max-width: 300px;">
                            <option value="approved">Approved (Active)</option>
                            <option value="pending">Pending Approval</option>
                            <option value="suspended">Suspended</option>
                        </select>
                    </div>
                </div>

                <div style="display: flex; gap: 12px; margin-top: 24px;">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Create User
                    </button>
                    <a href="users" class="btn btn-outline">Cancel</a>
                </div>
            </form>
        </div>
    </div>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
    $(document).ready(function() {
        // Load districts when region changes
        $('#regionSelect').on('change', function() {
            var regionId = $(this).val();
            var $districtSelect = $('#districtSelect');
            var $villageSelect = $('#villageSelect');

            $districtSelect.html('<option value="">-- Loading... --</option>').prop('disabled', true);
            $villageSelect.html('<option value="">-- Select Village --</option>').prop('disabled', true);

            if(regionId) {
                $.ajax({
                    url: '../api/get_locations.php',
                    data: { action: 'districts', region_id: regionId },
                    dataType: 'json',
                    success: function(response) {
                        var options = '<option value="">-- Select District --</option>';
                        if(response.success && response.data) {
                            response.data.forEach(function(item) {
                                options += '<option value="' + item.id + '">' + item.name + '</option>';
                            });
                        }
                        $districtSelect.html(options).prop('disabled', false);
                    },
                    error: function() {
                        $districtSelect.html('<option value="">-- Error loading --</option>');
                    }
                });
            }
        });

        // Load villages when district changes
        $('#districtSelect').on('change', function() {
            var districtId = $(this).val();
            var $villageSelect = $('#villageSelect');

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

            if(districtId) {
                $.ajax({
                    url: '../api/get_locations.php',
                    data: { action: 'villages', district_id: districtId },
                    dataType: 'json',
                    success: function(response) {
                        var options = '<option value="">-- Select Village --</option>';
                        options += '<option value="new">+ Add New Village/Street</option>';
                        if(response.success && response.data) {
                            response.data.forEach(function(item) {
                                options += '<option value="' + item.id + '">' + item.name + '</option>';
                            });
                        }
                        $villageSelect.html(options).prop('disabled', false);
                    },
                    error: function() {
                        $villageSelect.html('<option value="">-- Error loading --</option>');
                    }
                });
            }
        });

        // Show new village input when "Add New" is selected
        $('#villageSelect').on('change', function() {
            if($(this).val() === 'new') {
                $('#newVillageInput').show();
            } else {
                $('#newVillageInput').hide();
            }
        });
    });
    </script>
</body>
</html>
