<?php
require_once 'session_config_emp.php';
include_once 'connect.php';

// Ensure user is logged in
if (!isset($_SESSION['employee_id'])) {
    header('Location: login_emp.php');
    exit();
}

// Only allow POST requests
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    $_SESSION['password_change_error'] = "Invalid request method.";
    header("Location: employee_dashboard.php");
    exit();
}

// Get and sanitize inputs
$current_password = trim($_POST['current_password'] ?? '');
$new_password = trim($_POST['new_password'] ?? '');
$confirm_password = trim($_POST['confirm_password'] ?? '');

// Basic validation
if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
    $_SESSION['password_change_error'] = "All fields are required.";
    header("Location: employee_dashboard.php");
    exit();
}

if ($new_password !== $confirm_password) {
    $_SESSION['password_change_error'] = "New password and confirm password do not match.";
    header("Location: employee_dashboard.php");
    exit();
}

if (strlen($new_password) < 8) {
    $_SESSION['password_change_error'] = "New password must be at least 8 characters long.";
    header("Location: employee_dashboard.php");
    exit();
}

if ($new_password === $current_password) {
    $_SESSION['password_change_error'] = "New password cannot be the same as current password.";
    header("Location: employee_dashboard.php");
    exit();
}

$employee_id = $_SESSION['employee_id'];

try {
    // Fetch current hashed password
    $stmt = $conn->prepare("SELECT password, full_name FROM registrations_emp WHERE id = ?");
    $stmt->bind_param("i", $employee_id);
    $stmt->execute();
    $stmt->bind_result($hashed_password, $employee_name);
    
    if (!$stmt->fetch()) {
        $stmt->close();
        $_SESSION['password_change_error'] = "Employee not found.";
        header("Location: employee_dashboard.php");
        exit();
    }
    $stmt->close();

    // Verify current password
    if (!password_verify($current_password, $hashed_password)) {
        $_SESSION['password_change_error'] = "Current password is incorrect.";
        header("Location: employee_dashboard.php");
        exit();
    }
    
    // Hash new password
    $new_hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
    
    // Update password
    $update_stmt = $conn->prepare("UPDATE registrations_emp SET password = ?, last_password_change = NOW() WHERE id = ?");
    $update_stmt->bind_param("si", $new_hashed_password, $employee_id);
    
    if ($update_stmt->execute()) {
        // Log the password change (optional)
        $log_stmt = $conn->prepare("INSERT INTO emp_pswd_change_logs (employee_id, employee_name, change_date) VALUES (?, ?, NOW())");
        if ($log_stmt) {
            $log_stmt->bind_param("is", $employee_id, $employee_name);
            $log_stmt->execute();
            $log_stmt->close();
        }
        $update_stmt->close();
        
        // Show confirmation with JS and then logout
        echo "<script>
            alert('You have successfully changed your login password. Click OK to logout from the system and login with your new password.');
            window.location.href = 'login_emp.php';
        </script>";
        session_destroy();
        exit();
        
    } else {
        throw new Exception("Failed to update password: " . $update_stmt->error);
    }
    
} catch (Exception $e) {
    $_SESSION['password_change_error'] = "An error occurred: " . $e->getMessage();
    header("Location: employee_dashboard.php");
    exit();
}
?>