<?php
session_start();
require 'config.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'User not logged in'
    ]);
    exit;
}

// Check request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method'
    ]);
    exit;
}

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

// Validate input
if (!isset($input['current_password']) || !isset($input['new_password'])) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Current password and new password are required'
    ]);
    exit;
}

$currentPassword = $input['current_password'];
$newPassword = $input['new_password'];
$userId = $_SESSION['user_id'];

// Validate new password
if (strlen($newPassword) < 6) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'New password must be at least 6 characters long'
    ]);
    exit;
}

// Fetch current password hash from database
$sql = "SELECT password FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);

if (!$stmt) {
    error_log("Database prepare error: " . $conn->error);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Database error'
    ]);
    exit;
}

$stmt->bind_param("i", $userId);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

if (!$user) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'User not found'
    ]);
    exit;
}

// Verify current password
if (!password_verify($currentPassword, $user['password'])) {
    error_log("Password verification failed for user " . $userId);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Current password is incorrect'
    ]);
    exit;
}

// Hash new password
$hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);

// Update password in database
$updateSql = "UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?";
$updateStmt = $conn->prepare($updateSql);

if (!$updateStmt) {
    error_log("Database prepare error: " . $conn->error);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Database error'
    ]);
    exit;
}

$updateStmt->bind_param("si", $hashedPassword, $userId);

if ($updateStmt->execute()) {
    error_log("Password updated successfully for user " . $userId);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'message' => 'Password changed successfully'
    ]);
} else {
    error_log("Password update failed for user " . $userId . ": " . $updateStmt->error);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Failed to update password: ' . $updateStmt->error
    ]);
}

$updateStmt->close();
$conn->close();
?>
