<?php
session_start();
include('../includes/config.php');

if (!isset($_SESSION['user_id'])) {
    header("Location: ../index.php");
    exit();
}

$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    $data = json_decode(file_get_contents('php://input'), true);
    $new_pass = trim($data['new_password'] ?? '');
    $confirm_pass = trim($data['confirm_password'] ?? '');

    if (strlen($new_pass) < 6) {
        echo json_encode(['success' => false, 'message' => 'Password must be at least 6 characters.']);
        exit;
    }

    if ($new_pass !== $confirm_pass) {
        echo json_encode(['success' => false, 'message' => 'Passwords do not match.']);
        exit;
    }

    if (password_verify("Reset123!", $new_pass)) {
        echo json_encode(['success' => false, 'message' => 'New password cannot be the default password.']);
        exit;
    }

    $hashed = password_hash($new_pass, PASSWORD_DEFAULT);
    $stmt = $conn->prepare("UPDATE users SET password = ?, password_reset = 0, password_changed = 1 WHERE id = ?");
    $stmt->bind_param("si", $hashed, $user_id);

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Password updated successfully.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update password.']);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Change Password - Digital POS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            margin: 0;
            font-family: 'Segoe UI', sans-serif;
            background: url('../images/bg.jpg') no-repeat center center fixed;
            background-size: cover;
        }

        .form-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: rgba(0, 0, 0, 0.6);
        }

        .form-box {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            padding: 40px;
            border-radius: 10px;
            width: 90%;
            max-width: 400px;
            color: #fff;
            text-align: center;
        }

        .form-box h2 {
            margin-bottom: 20px;
        }

        .form-box p {
            margin-bottom: 20px;
        }

        input[type="password"], button {
            width: 100%;
            padding: 12px;
            margin: 10px 0;
            border-radius: 8px;
            border: none;
            font-size: 16px;
        }

        button {
            background: orange;
            color: black;
            font-weight: bold;
            cursor: pointer;
            border: none;
        }

        button:hover {
            background-color: #ff9900;
        }

        .message {
            margin-top: 15px;
            font-weight: bold;
            color: #ff4d4d;
        }

        @media (max-width: 600px) {
            .form-box {
                padding: 30px 20px;
            }
        }
    </style>
</head>
<body>

<div class="form-container">
    <div class="form-box">
        <h2>Change Password</h2>
        <p>You must set a new password before continuing.</p>
        <form id="changePassForm">
            <input type="password" name="new_password" placeholder="New Password" required />
            <input type="password" name="confirm_password" placeholder="Confirm Password" required />
            <button type="submit">Update Password</button>
            <div class="message" id="responseMsg"></div>
        </form>
    </div>
</div>

<script>
document.getElementById('changePassForm').addEventListener('submit', function (e) {
    e.preventDefault();

    const form = e.target;
    const newPassword = form.new_password.value.trim();
    const confirmPassword = form.confirm_password.value.trim();
    const msg = document.getElementById('responseMsg');

    fetch('change_password.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ new_password: newPassword, confirm_password: confirmPassword })
    })
    .then(res => res.json())
    .then(data => {
        msg.textContent = data.message;
        msg.style.color = data.success ? 'limegreen' : 'red';
        if (data.success) {
            setTimeout(() => {
                window.location.href = 'redirect_user.php';
            }, 1500);
        }
    })
    .catch(() => {
        msg.textContent = 'Network error occurred.';
        msg.style.color = 'red';
    });
});
</script>

</body>
</html>
