<?php
/**
 * Rig N Dig - Mobile API v1 / Login
 */
header('Content-Type: application/json');
require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once 'api_helper.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    apiResponse(false, 'Invalid request method.');
}

$email = sanitize($_POST['email'] ?? '');
$pass  = $_POST['password'] ?? '';

if (!$email || !$pass) {
    apiResponse(false, 'Email and Password required.');
}

$customer = Database::fetchOne("SELECT * FROM customers WHERE email = ? AND status = 'active'", [$email]);

if ($customer && password_verify($pass, $customer['password'])) {
    
    // Generate API Token for Mobile Persistence
    $token = generateApiToken($customer['id']);
    
    // Log Activity
    logActivity('customer', $customer['id'], 'API Login', 'Logged in via Mobile App');

    apiResponse(true, 'Login Successful', [
        'token' => $token,
        'user' => [
            'id' => $customer['id'],
            'name' => $customer['contact_name'],
            'company' => $customer['company_name'],
            'email' => $customer['email'],
            'phone' => $customer['phone']
        ]
    ]);
} else {
    apiResponse(false, 'Invalid login credentials.');
}
