<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/db.php';

// 🔒 Extract token from Authorization header
$headers = getallheaders();
$token = $headers['Authorization'] ?? '';

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'Missing token']);
    exit;
}

// 🔒 Validate token and get user
$stmt = $pdo->prepare("SELECT * FROM users WHERE token = ?");
$stmt->execute([$token]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    http_response_code(403);
    echo json_encode(['error' => 'Invalid token']);
    exit;
}

// ✅ Parse JSON input
$data = json_decode(file_get_contents("php://input"), true);

$bill_id        = intval($data['bill_id'] ?? 0);
$amount         = floatval($data['amount'] ?? 0);
$payment_date   = $data['payment_date'] ?? date('Y-m-d');
$method         = $data['method'] ?? 'Cash';
$send_sms       = $data['send_sms'] ?? false;

if ($bill_id <= 0 || $amount <= 0 || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $payment_date)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid input']);
    exit;
}

try {
    // 💾 Record payment
    $stmt = $pdo->prepare("INSERT INTO payments (bill_id, amount, payment_date, method) VALUES (?, ?, ?, ?)");
    $stmt->execute([$bill_id, $amount, $payment_date, $method]);

    // 🔍 Fetch bill & customer info
    $stmt = $pdo->prepare("
        SELECT b.bill_number, c.name, c.contact_number,
               COALESCE((SELECT SUM(j.total) FROM jobs j WHERE j.bill_id = b.bill_id), 0) AS grand_total,
               COALESCE((SELECT SUM(p.amount) FROM payments p WHERE p.bill_id = b.bill_id), 0) AS total_paid
        FROM bills b
        JOIN customers c ON b.customer_id = c.customer_id
        WHERE b.bill_id = ?
    ");
    $stmt->execute([$bill_id]);
    $bill = $stmt->fetch(PDO::FETCH_ASSOC);

    // 📲 Optional SMS
    if ($send_sms && $bill) {
        $balance = max(0, $bill['grand_total'] - $bill['total_paid']);
        $formattedAmount = number_format($amount, 2);
        $formattedBalance = number_format($balance, 2);
        $phone = preg_replace('/^0/', '+94', $bill['contact_number']);
        $message = $balance > 0 ?
            "Dear {$bill['name']}, your payment of Rs. $formattedAmount for Bill #{$bill['bill_number']} was received.\nBalance: Rs. $formattedBalance.\nCall 0770233310 for queries. - WashHouse" :
            "Dear {$bill['name']}, your payment of Rs. $formattedAmount for Bill #{$bill['bill_number']} was received. No balance due.\nCall 0770233310 for queries. - WashHouse";

        $smsData = [
            'user_id'   => '190',
            'api_key'   => '7b57b3bb-172e-43c7-9aed-a5f417c9fd2c',
            'sender_id' => 'WashHouse',
            'contact'   => $phone,
            'message'   => $message
        ];

        $ch = curl_init('https://smslenz.lk/api/send-sms');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($smsData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $smsResponse = curl_exec($ch);
        curl_close($ch);
    }

    echo json_encode(['success' => true, 'message' => 'Payment recorded' . ($send_sms ? ' and SMS sent.' : '.')]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
