<?php
require_once 'config/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

requireLogin();

$user = getCurrentUser($conn);
$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_profile') {
    $email = htmlspecialchars($_POST['email'] ?? '', ENT_QUOTES);
    $phone = htmlspecialchars($_POST['phone'] ?? '', ENT_QUOTES);
    $full_name = htmlspecialchars($_POST['full_name'] ?? '', ENT_QUOTES);

    if (empty($full_name)) {
        $errors[] = 'Full name is required';
    }

    if (empty($errors)) {
        try {
            $sql = "UPDATE users SET email = ?, phone = ?, full_name = ? WHERE id = ?";
            executeQuery($conn, $sql, [$email, $phone, $full_name, $_SESSION['user_id']], "sssi");
            
            $_SESSION['full_name'] = $full_name;
            $success = 'Profile updated successfully';
            $user = getCurrentUser($conn);
        } catch (Exception $e) {
            $errors[] = 'Error updating profile: ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'change_password') {
    $old_password = $_POST['old_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if (empty($old_password)) {
        $errors[] = 'Current password is required';
    }
    if (empty($new_password)) {
        $errors[] = 'New password is required';
    }
    if (strlen($new_password) < 8) {
        $errors[] = 'New password must be at least 8 characters';
    }
    if ($new_password !== $confirm_password) {
        $errors[] = 'Passwords do not match';
    }

    // Bug fix: verify old password using password_verify (supports bcrypt + legacy)
    if (!$errors) {
        $dbUser = fetchOne($conn, "SELECT password FROM users WHERE id = ?", [$_SESSION['user_id']], "i");
        $stored = $dbUser['password'] ?? '';
        $validOld = password_get_info($stored)['algo']
            ? password_verify($old_password, $stored)
            : ($old_password === $stored);
        if (!$validOld) {
            $errors[] = 'Current password is incorrect';
        }
    }

    if (empty($errors)) {
        try {
            $hashed_password = hashPassword($new_password);
            $sql = "UPDATE users SET password = ? WHERE id = ?";
            executeQuery($conn, $sql, [$hashed_password, $_SESSION['user_id']], "si");
            
            $success = 'Password changed successfully';
        } catch (Exception $e) {
            $errors[] = 'Error changing password: ' . $e->getMessage();
        }
    }
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<div class="row mb-4">
    <div class="col-lg-12">
        <h3><i class="fas fa-user-circle"></i> My Profile</h3>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <i class="fas fa-exclamation-circle"></i> Please correct the following errors:
        <ul class="mb-0 mt-2">
            <?php foreach ($errors as $error): ?>
                <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="row">
    <div class="col-lg-8">
        <!-- Profile Information -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">Profile Information</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="">
                    <input type="hidden" name="action" value="update_profile">
                    
                    <div class="mb-3">
                        <label for="full_name" class="form-label">Full Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="full_name" name="full_name" required
                               value="<?php echo htmlspecialchars($user['full_name']); ?>">
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="email" class="form-label">Email</label>
                            <input type="email" class="form-control" id="email" name="email"
                                   value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="phone" class="form-label">Phone</label>
                            <input type="tel" class="form-control" id="phone" name="phone"
                                   value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                        </div>
                    </div>

                    <div class="d-flex gap-2 mt-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Update Profile
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Change Password -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Change Password</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="">
                    <input type="hidden" name="action" value="change_password">
                    
                    <div class="mb-3">
                        <label for="old_password" class="form-label">Current Password <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" id="old_password" name="old_password" required
                               placeholder="Enter your current password">
                    </div>

                    <div class="mb-3">
                        <label for="new_password" class="form-label">New Password <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" id="new_password" name="new_password" required
                               placeholder="Min 6 characters">
                        <small class="form-text text-muted">Must be at least 6 characters</small>
                    </div>

                    <div class="mb-3">
                        <label for="confirm_password" class="form-label">Confirm Password <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" required
                               placeholder="Repeat your new password">
                    </div>

                    <div class="d-flex gap-2 mt-4">
                        <button type="submit" class="btn btn-warning">
                            <i class="fas fa-lock"></i> Change Password
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- User Info Card -->
    <div class="col-lg-4">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">Account Information</h5>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="text-muted">Username</label>
                    <h6><code><?php echo htmlspecialchars($user['username']); ?></code></h6>
                </div>

                <div class="mb-3">
                    <label class="text-muted">Role</label>
                    <h6>
                        <span class="badge <?php echo $user['role'] === 'admin' ? 'bg-danger' : 'bg-info'; ?>">
                            <?php echo ucfirst($user['role']); ?>
                        </span>
                    </h6>
                </div>

                <div class="mb-3">
                    <label class="text-muted">Member Since</label>
                    <h6><?php echo date('M d, Y', strtotime($user['created_at'] ?? 'now')); ?></h6>
                </div>

                <hr>

                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i>
                    <small>Keep your password secure and unique. Never share your credentials with others.</small>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Quick Actions</h5>
            </div>
            <div class="card-body">
                <a href="/cash_lending/dashboard.php" class="btn btn-outline-primary w-100 mb-2">
                    <i class="fas fa-chart-line"></i> Go to Dashboard
                </a>
                <a href="/cash_lending/logout.php" class="btn btn-outline-danger w-100">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
