<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

require_once '../config/database.php';

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    // Validate required fields
    if (empty($input['mobile']) || empty($input['password'])) {
        throw new Exception('Mobile number and password are required');
    }
    
    // Validate mobile number format
    if (!preg_match('/^[0-9]{10}$/', $input['mobile'])) {
        throw new Exception('Invalid mobile number format');
    }
    
    $pdo = getDBConnection();
    
    // Get user by mobile number
    $stmt = $pdo->prepare("
        SELECT id, name, mobile, city, password 
        FROM users 
        WHERE mobile = ?
    ");
    $stmt->execute([$input['mobile']]);
    $user = $stmt->fetch();
    
    if (!$user) {
        throw new Exception('Invalid mobile number or password');
    }
    
    // Verify password
    if (!password_verify($input['password'], $user['password'])) {
        throw new Exception('Invalid mobile number or password');
    }
    
    // Remove password from response
    unset($user['password']);
    
    echo json_encode([
        'success' => true,
        'message' => 'Login successful',
        'user' => $user
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}
?> 