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

require 'includes/db.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    exit;
}

// Read JSON input
$input = json_decode(file_get_contents('php://input'), true);

$oldPassword = $input['old_password'] ?? '';
$newPassword = $input['new_password'] ?? '';
$confirmPassword = $input['confirm_password'] ?? '';

if (!$oldPassword || !$newPassword || !$confirmPassword) {
    http_response_code(400);
    echo json_encode(['error' => 'All fields are required']);
    exit;
}

// Fetch current hashed password
$stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || !password_verify($oldPassword, $user['password'])) {
    echo json_encode(['error' => 'Old password is incorrect']);
    exit;
}

if ($newPassword !== $confirmPassword) {
    echo json_encode(['error' => 'New passwords do not match']);
    exit;
}

if (strlen($newPassword) < 6) {
    echo json_encode(['error' => 'Password must be at least 6 characters']);
    exit;
}

// Update password
$newHash = password_hash($newPassword, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
$stmt->execute([$newHash, $user_id]);

echo json_encode(['success' => 'Password changed successfully']);
