<?php
// FINAL SCRIPT v5: Corrected Column Name

ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
require 'db_connect.php';

header('Content-Type: application/json');
ob_clean();

$response = [];

$mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
$code = isset($_POST['code']) ? trim($_POST['code']) : '';
$new_password = isset($_POST['new_password']) ? trim($_POST['new_password']) : '';

if (empty($mobile) || empty($code) || empty($new_password)) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = 'Missing required fields.';
    echo json_encode($response);
    exit;
}

$normalized_mobile = substr($mobile, -10);

try {
    $sql_check = "SELECT id FROM users WHERE mobile LIKE CONCAT('%', ?) AND reset_code = ?";
    $stmt_check = $conn->prepare($sql_check);
    $stmt_check->bind_param("ss", $normalized_mobile, $code);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();

    if ($result_check->num_rows > 0) {
        $user = $result_check->fetch_assoc();
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

        // --- THE FINAL FIX ---
        // Changed 'password' to 'password_hash' to match your database table.
        $sql_update = "UPDATE users SET password_hash = ?, reset_code = NULL WHERE id = ?";
        
        $stmt_update = $conn->prepare($sql_update);
        $stmt_update->bind_param("si", $hashed_password, $user['id']);
        $stmt_update->execute();
        $stmt_update->close();

        $response['status'] = 'success';
        $response['message'] = 'Password has been reset successfully.';
        echo json_encode($response);

    } else {
        http_response_code(400);
        $response['status'] = 'error';
        $response['message'] = 'Invalid reset code.';
        echo json_encode($response);
    }
    $stmt_check->close();

} catch (Exception $e) {
    // This is where the "Unknown column" error was being caught.
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'An internal server error occurred: ' . $e->getMessage();
    error_log("Password Reset CRITICAL ERROR: " . $e->getMessage()); 
    echo json_encode($response);
}

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