<?php
/**
 * Village - Change My Password
 * Allows village users to change their own password
 */

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

// Check if user is logged in with village role
$allowed_roles = ['village_chairman', 'land_officer', 'surveyor', 'district_officer', 'land_council'];
if(!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header('Location: ../login');
    exit;
}

$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

// Get current user
$stmt = $conn->prepare("SELECT id, username, full_name, password FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

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

// Handle password change
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if(empty($current_password)) {
        $error = 'Tafadhali ingiza nywila yako ya sasa / Please enter your current password';
    } elseif(!password_verify($current_password, $user['password'])) {
        $error = 'Nywila ya sasa si sahihi / Current password is incorrect';
    } elseif(strlen($new_password) < 6) {
        $error = 'Nywila mpya lazima iwe na herufi 6 au zaidi / New password must be at least 6 characters';
    } elseif($new_password !== $confirm_password) {
        $error = 'Nywila mpya hazilingani / New passwords do not match';
    } else {
        // Hash and update password
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

        $update_stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
        $update_stmt->bind_param("si", $hashed_password, $user_id);

        if($update_stmt->execute()) {
            // Log activity
            $log_desc = "User changed their own password";
            mysqli_query($conn, "INSERT INTO activity_logs (user_id, action, description, ip_address) VALUES ($user_id, 'password_changed', '$log_desc', '{$_SERVER['REMOTE_ADDR']}')");

            $success = 'Nywila imebadilishwa kikamilifu! / Password changed successfully!';
        } else {
            $error = 'Imeshindikana kubadilisha nywila / Failed to change password';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Badilisha Nywila - Change Password</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">
    <style>
        :root {
            --village-gradient: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            --primary: #11998e;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f1f5f9;
            margin: 0;
            min-height: 100vh;
        }

        .admin-main {
            margin-left: 280px;
            padding: 30px;
            min-height: 100vh;
        }

        @media (max-width: 1024px) {
            .admin-main {
                margin-left: 0;
                padding: 20px;
                padding-top: 90px;
            }
        }

        .page-header {
            background: var(--village-gradient);
            border-radius: 16px;
            padding: 30px;
            margin-bottom: 24px;
            color: white;
        }

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

        .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: 500px;
        }

        .user-info {
            background: linear-gradient(135deg, rgba(17, 153, 142, 0.1) 0%, rgba(56, 239, 125, 0.1) 100%);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 24px;
            border: 1px solid rgba(17, 153, 142, 0.2);
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .user-avatar {
            width: 56px;
            height: 56px;
            border-radius: 14px;
            background: var(--village-gradient);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
            font-weight: 700;
        }

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

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

        .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;
            box-sizing: border-box;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(17, 153, 142, 0.1);
        }

        .password-input {
            position: relative;
        }

        .password-input .toggle-password {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #94a3b8;
            cursor: pointer;
            padding: 4px;
        }

        .password-input .toggle-password:hover {
            color: var(--primary);
        }

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

        .btn-primary {
            background: var(--village-gradient);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(17, 153, 142, 0.4);
        }

        .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;
            border: 1px solid #c3e6cb;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .password-requirements {
            background: #fffbeb;
            border: 1px solid #fcd34d;
            border-radius: 10px;
            padding: 14px 18px;
            margin-bottom: 20px;
        }

        .password-requirements h5 {
            font-size: 13px;
            font-weight: 600;
            color: #92400e;
            margin: 0 0 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .password-requirements ul {
            margin: 0;
            padding-left: 20px;
            font-size: 12px;
            color: #78350f;
        }

        .password-requirements li {
            margin-bottom: 4px;
        }

        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: #64748b;
            text-decoration: none;
            font-size: 14px;
            margin-bottom: 16px;
            transition: color 0.2s;
        }

        .back-link:hover {
            color: var(--primary);
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="admin-main">
        <a href="dashboard" class="back-link">
            <i class="fas fa-arrow-left"></i> Rudi Dashboard / Back to Dashboard
        </a>

        <div class="page-header">
            <h1><i class="fas fa-key"></i> Badilisha Nywila / Change Password</h1>
            <p>Badilisha nywila ya akaunti yako / Change your account password</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">
            <div class="user-info">
                <div class="user-avatar">
                    <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
                </div>
                <div>
                    <h4><?php echo htmlspecialchars($user['full_name'] ?: $user['username']); ?></h4>
                    <p><i class="fas fa-user"></i> @<?php echo htmlspecialchars($user['username']); ?></p>
                </div>
            </div>

            <div class="password-requirements">
                <h5><i class="fas fa-info-circle"></i> Mahitaji ya Nywila / Password Requirements</h5>
                <ul>
                    <li>Herufi 6 au zaidi / At least 6 characters</li>
                    <li>Tumia mchanganyiko wa herufi na nambari / Mix of letters and numbers recommended</li>
                </ul>
            </div>

            <form method="POST" id="passwordForm">
                <div class="form-group">
                    <label class="form-label">Nywila ya Sasa / Current Password *</label>
                    <div class="password-input">
                        <input type="password" name="current_password" id="current_password" class="form-control" required placeholder="Ingiza nywila yako ya sasa">
                        <button type="button" class="toggle-password" onclick="togglePassword('current_password', this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Nywila Mpya / New Password *</label>
                    <div class="password-input">
                        <input type="password" name="new_password" id="new_password" class="form-control" required placeholder="Ingiza nywila mpya (herufi 6+)" minlength="6">
                        <button type="button" class="toggle-password" onclick="togglePassword('new_password', this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Thibitisha Nywila / Confirm Password *</label>
                    <div class="password-input">
                        <input type="password" name="confirm_password" id="confirm_password" class="form-control" required placeholder="Ingiza nywila mpya tena" minlength="6">
                        <button type="button" class="toggle-password" onclick="togglePassword('confirm_password', this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>

                <div style="display: flex; gap: 12px; margin-top: 24px;">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Badilisha Nywila / Change Password
                    </button>
                    <a href="dashboard" class="btn btn-outline">Ghairi / Cancel</a>
                </div>
            </form>
        </div>
    </main>

    <script>
        function togglePassword(inputId, btn) {
            const input = document.getElementById(inputId);
            const icon = btn.querySelector('i');

            if(input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }

        // Validate passwords match before submit
        document.getElementById('passwordForm').addEventListener('submit', function(e) {
            const newPass = document.getElementById('new_password').value;
            const confirmPass = document.getElementById('confirm_password').value;

            if(newPass !== confirmPass) {
                e.preventDefault();
                alert('Nywila mpya hazilingani! / New passwords do not match!');
            }
        });
    </script>
</body>
</html>
