<?php
// FINAL CORRECTED SCRIPT: login_user.php

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 = [];

if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Database connection failed.';
    echo json_encode($response);
    exit;
}

if (!isset($_POST['mobile']) || !isset($_POST['password'])) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = 'Mobile and password are required.';
    echo json_encode($response);
    exit;
}

$mobile = trim($_POST['mobile']);
$password = $_POST['password'];

try {
    // THE FIX: Select the 'password_hash' column
    $sql = "SELECT id, name, mobile, address, role, password_hash FROM users WHERE mobile = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $mobile);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    // THE FIX: Verify the password against the 'password_hash' column
    if ($user && password_verify($password, $user['password_hash'])) {
        // Password is correct, send back user data (without the hash)
        unset($user['password_hash']);
        echo json_encode($user);
    } else {
        // Invalid credentials
        http_response_code(401); // Unauthorized
        $response['status'] = 'error';
        $response['message'] = 'Invalid mobile number or password.';
        echo json_encode($response);
    }
    $stmt->close();

} catch (Exception $e) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: ' . $e->getMessage();
    echo json_encode($response);
}

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