<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();
require_once("../config/config.php");

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

$user_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($user_id <= 0) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>No User Selected</h2>");
}

// Fetch User Details
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>User Not Found</h2>");
}

$success = "";
$error = "";

// Handle Form Submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $full_name    = trim($_POST['full_name'] ?? '');
    $email        = trim($_POST['email'] ?? '');
    $phone        = trim($_POST['phone'] ?? '');
    $role         = $_POST['role'] ?? 'user';
    $department   = trim($_POST['department'] ?? '');
    $status       = $_POST['status'] ?? 'Active';
    $new_password = $_POST['new_password'] ?? '';

    if (empty($full_name)) {
        $error = "Full Name is required.";
    } elseif (empty($email)) {
        $error = "Email is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } else {
        try {
            // Check if email exists for another user
            $check = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
            $check->bind_param("si", $email, $user_id);
            $check->execute();
            if ($check->get_result()->num_rows > 0) {
                $error = "This email is already in use by another user.";
            } else {
                if (!empty($new_password) && strlen($new_password) >= 6) {
                    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                    $stmt = $conn->prepare("
                        UPDATE users SET 
                            full_name = ?, email = ?, phone = ?, role = ?, 
                            department = ?, status = ?, password = ?, updated_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->bind_param("sssssssi", 
                        $full_name, $email, $phone, $role, 
                        $department, $status, $hashed_password, $user_id
                    );
                } else {
                    $stmt = $conn->prepare("
                        UPDATE users SET 
                            full_name = ?, email = ?, phone = ?, role = ?, 
                            department = ?, status = ?, updated_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->bind_param("ssssssi", 
                        $full_name, $email, $phone, $role, 
                        $department, $status, $user_id
                    );
                }

                if ($stmt->execute()) {
                    $success = "User updated successfully!";
                    header("Location: user-edit.php?id=$user_id&success=1");
                    exit();
                } else {
                    throw new Exception($stmt->error);
                }
            }
        } catch (Exception $e) {
            $error = "Error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit User - <?= htmlspecialchars($user['full_name']) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.10);
            --glass-border: rgba(255,255,255,0.20);
        }
        * { margin:0; padding:0; box-sizing:border-box; }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), 
                        url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
            min-height: 100vh;
        }

        .container { max-width: 680px; margin: auto; width: 100%; }

        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 32px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 30px 80px rgba(0,0,0,0.65);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
            padding: 50px 40px;
            text-align: center;
        }
        .header h1 {
            font-size: clamp(26px, 5vw, 38px);
            font-weight: 700;
        }

        .form-area { padding: 45px 40px; }

        .message {
            padding: 16px 24px;
            border-radius: 16px;
            margin-bottom: 30px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .success { background: rgba(34,197,94,0.25); border:1px solid #4ade80; color:#86efac; }
        .error   { background: rgba(239,68,68,0.25); border:1px solid #f87171; color:#fca5a5; }

        label {
            display: block;
            margin-bottom: 10px;
            font-weight: 600;
            color: #e0e7ff;
        }
        .required { color: #f87171; }

        .password-wrapper {
            position: relative;
        }
        input, select {
            width: 100%;
            padding: 16px 20px;
            background: rgba(255,255,255,0.09);
            border: 1px solid rgba(255,255,255,0.25);
            border-radius: 16px;
            color: white;
            font-size: 16px;
        }
        input:focus, select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(168,85,247,0.25);
            background: rgba(255,255,255,0.15);
        }
        option{
            color:black;
         }
        .toggle-password {
            position: absolute;
            right: 18px;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
            cursor: pointer;
            font-size: 1.1rem;
        }

        .grid-2 {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
        }

        .submit-btn {
            width: 100%;
            padding: 19px;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border: none;
            border-radius: 16px;
            font-size: 1.15rem;
            font-weight: 700;
            cursor: pointer;
            margin-top: 25px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
        }

        .submit-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 20px 50px rgba(168,85,247,0.5);
        }

        @media (max-width: 640px) {
            .glass-container { border-radius: 24px; }
            .header, .form-area { padding: 35px 25px; }
        }
    </style>
</head>
<body>

<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">
        <div class="header">
            <a href="users-list.php" style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:50px;">
                ← Back to Users
            </a>
            <h1><i class="fas fa-user-edit"></i> Edit User</h1>
            <p style="margin-top:12px; opacity:0.9;">
                <?= htmlspecialchars($user['user_code']) ?> — <?= htmlspecialchars($user['full_name']) ?>
            </p>
        </div>

        <div class="form-area">
            <?php if ($success || isset($_GET['success'])): ?>
                <div class="message success">
                    <i class="fas fa-check-circle"></i> User updated successfully!
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="message error">
                    <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <form method="post" autocomplete="off">

                <div class="form-group">
                    <label>User Code</label>
                    <input type="text" value="<?= htmlspecialchars($user['user_code']) ?>" readonly>
                </div>

                <div class="form-group">
                    <label>Full Name <span class="required">*</span></label>
                    <input type="text" name="full_name" 
                           value="<?= htmlspecialchars($user['full_name']) ?>" 
                           required>
                </div>

                <div class="form-group">
                    <label>Email Address <span class="required">*</span></label>
                    <input type="email" name="email" 
                           value="<?= htmlspecialchars($user['email']) ?>" 
                           required>
                </div>

                <!-- Password Field with Toggle -->
                <div class="form-group">
                    <label>New Password <small>(Leave blank to keep current password)</small></label>
                    <div class="password-wrapper">
                        <input type="password" name="new_password" id="new_password" 
                               placeholder="Minimum 6 characters (optional)">
                        <span class="toggle-password" id="togglePassword">
                            <i class="fas fa-eye"></i>
                        </span>
                    </div>
                </div>

                <div class="grid-2">
                    <div class="form-group">
                        <label>Phone Number</label>
                        <input type="tel" name="phone" 
                               value="<?= htmlspecialchars($user['phone'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label>Department</label>
                        <input type="text" name="department" 
                               value="<?= htmlspecialchars($user['department'] ?? '') ?>">
                    </div>
                </div>

                <div class="grid-2">
                    <div class="form-group">
                        <label>Role <span class="required">*</span></label>
                        <select name="role" required>
                            <option value="admin" <?= $user['role'] === 'admin' ? 'selected' : '' ?>>Admin</option>
                            <option value="project manager" <?= $user['role'] === 'project manager' ? 'selected' : '' ?>>Project Manager</option>
                            <option value="store manager" <?= $user['role'] === 'store manager' ? 'selected' : '' ?>>Store Manager</option>
                            <option value="accountant" <?= $user['role'] === 'accountant' ? 'selected' : '' ?>>Accountant</option>
                            <option value="user" <?= $user['role'] === 'user' ? 'selected' : '' ?>>User</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Status</label>
                        <select name="status">
                            <option value="Active" <?= $user['status'] === 'Active' ? 'selected' : '' ?>>Active</option>
                            <option value="Inactive" <?= $user['status'] === 'Inactive' ? 'selected' : '' ?>>Inactive</option>
                            <option value="Suspended" <?= $user['status'] === 'Suspended' ? 'selected' : '' ?>>Suspended</option>
                        </select>
                    </div>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-save"></i> Update User
                </button>
            </form>
        </div>
    </div>
</div>

<script>
// Show/Hide Password Toggle
document.getElementById('togglePassword').addEventListener('click', function () {
    const passwordField = document.getElementById('new_password');
    const icon = this.querySelector('i');

    if (passwordField.type === 'password') {
        passwordField.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        passwordField.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
});
</script>

</body>
</html>

<?php $conn->close(); ?>