<?php
session_start();

header("Access-Control-Allow-Origin: https://enerliths.com");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}
require "../config/db.php";



$user_id = $_SESSION["user_id"];

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

$current = $data["current"];
$new = $data["new"];

if(!$current || !$new){
 echo json_encode(["status"=>"error","message"=>"Missing fields"]);
 exit;
}

/* GET USER PASSWORD */

$stmt = $conn->prepare("SELECT password FROM users WHERE id=?");
$stmt->bind_param("i",$user_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();

if(!$result){
 echo json_encode(["status"=>"error","message"=>"User not found"]);
 exit;
}

/* VERIFY CURRENT PASSWORD */

if(!password_verify($current,$result["password"])){
 echo json_encode(["status"=>"error","message"=>"Current password is incorrect"]);
 exit;
}

/* HASH NEW PASSWORD */

$hash = password_hash($new,PASSWORD_DEFAULT);

$stmt = $conn->prepare("UPDATE users SET password=? WHERE id=?");
$stmt->bind_param("si",$hash,$user_id);
$stmt->execute();

echo json_encode([
 "status"=>"success",
 "message"=>"Password updated successfully"
]);