<?php
header('Content-Type: application/json');

include_once __DIR__ . '/../../config/dbcon.php';
include_once __DIR__ . '/../../helpers/api_helper.php';

session_start();

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, "Invalid request method.");
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    sendResponse(401, "Unauthorized. Please login first.");
}

// Get JSON data
$data = json_decode(file_get_contents("php://input"), true);

$oldPassword = $data['old_password'] ?? '';
$newPassword = $data['new_password'] ?? '';
$confirmPassword = $data['confirm_password'] ?? '';
$userId = $_SESSION['user_id'];

// Validation
if (!$oldPassword || !$newPassword || !$confirmPassword) {
    sendResponse(422, "All fields are required.");
}

// Check if new passwords match
if ($newPassword !== $confirmPassword) {
    sendResponse(422, "New password and confirm password do not match.");
}

// Validate new password strength
if (strlen($newPassword) < 6) {
    sendResponse(422, "New password must be at least 6 characters long.");
}

// Check if new password is same as old password
if ($oldPassword === $newPassword) {
    sendResponse(422, "New password cannot be the same as old password.");
}

try {
    // Fetch current password hash from database
    $stmt = $conn->prepare("SELECT password FROM users WHERE id = ? AND deleted_at IS NULL");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        sendResponse(404, "User not found.");
    }

    // Verify old password
    if (!password_verify($oldPassword, $user['password'])) {
        sendResponse(401, "Old password is incorrect.");
    }

    // Hash new password
    $newPasswordHash = password_hash($newPassword, PASSWORD_DEFAULT);

    // Update password in database
    $stmt = $conn->prepare("UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$newPasswordHash, $userId]);

    if ($stmt->rowCount() > 0) {
        sendResponse(200, "Password changed successfully!");
    } else {
        sendResponse(500, "Failed to change password.");
    }

} catch (PDOException $e) {
    sendResponse(500, "Database error: " . $e->getMessage());
}
?>