<?php
// printshop/api/login.php

ini_set('display_errors', 1);
error_reporting(E_ALL);

include_once('../../includes/db.php');
header("Content-Type: application/json");

// Accept both 'phone' or fallback to legacy 'email'
$phone = $_POST['phone'] ?? $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';

// Sanitize inputs
$phone = mysqli_real_escape_string($conn, trim($phone));
$password = trim($password);

if (!empty($phone) && !empty($password)) {
    // ✅ Authenticate by phone number
$normalizedPhone = str_replace('+973', '', $phone); // strip +973 if included
$user = fetchOne("SELECT * FROM users WHERE phone = '$phone' OR phone = '$normalizedPhone'");

    if ($user && password_verify($password, $user['password'])) {
        echo json_encode([
            "status" => true,
            "message" => "Login successful.",
            "user" => [
                "id" => $user['id'],
                "name" => $user['name'],
                "email" => $user['email'],
                "phone" => $user['phone']
            ]
        ]);
    } else {
        echo json_encode(["status" => false, "message" => "Invalid phone number or password."]);
    }
} else {
    echo json_encode(["status" => false, "message" => "Missing required fields."]);
}
