<?php
// ajax/save_payment.php
error_reporting(0);
require_once __DIR__ . '/../config/db.php';
startSession();
header('Content-Type: application/json');

$user    = getCurrentUser();
$user_id = $user['user_id'];
$sid     = (int)($_POST['submission_id'] ?? 0);
$data    = json_decode($_POST['data'] ?? '{}', true);

if (!$sid || !is_array($data)) {
    echo json_encode(['success'=>false,'message'=>'Invalid request']); exit;
}

// Verify ownership
try {
    $q = db()->prepare("SELECT submission_id FROM submissions WHERE submission_id=? AND user_id=?");
    $q->execute([$sid, $user_id]);
    if (!$q->fetch()) {
        echo json_encode(['success'=>false,'message'=>'Access denied']); exit;
    }
} catch(PDOException $e) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]); exit;
}

try {
    // Ensure table exists
    db()->exec("CREATE TABLE IF NOT EXISTS submission_payment (
        payment_id         INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        submission_id      INT UNSIGNED NOT NULL UNIQUE,
        billing_email      VARCHAR(200) NULL,
        phone_country_code VARCHAR(10)  DEFAULT '+91',
        phone_number       VARCHAR(30)  NULL,
        address            TEXT         NULL,
        city               VARCHAR(100) NULL,
        zip_code           VARCHAR(30)  NULL,
        country_region     VARCHAR(100) NULL,
        billing_reference  TEXT         NULL,
        fee_agreed         TINYINT(1)   DEFAULT 0,
        updated_at         DATETIME     DEFAULT NOW() ON UPDATE NOW()
    )");

    // Check if row exists
    $q = db()->prepare("SELECT payment_id FROM submission_payment WHERE submission_id=?");
    $q->execute([$sid]);
    $exists = $q->fetchColumn();

    if ($exists) {
        db()->prepare(
            "UPDATE submission_payment SET
                billing_email=?, phone_country_code=?, phone_number=?,
                address=?, city=?, zip_code=?, country_region=?,
                billing_reference=?, fee_agreed=?, updated_at=NOW()
             WHERE submission_id=?"
        )->execute([
            trim($data['billing_email']      ?? ''),
            trim($data['phone_country_code'] ?? ''),
            trim($data['phone_number']       ?? ''),
            trim($data['address']            ?? ''),
            trim($data['city']               ?? ''),
            trim($data['zip_code']           ?? ''),
            trim($data['country_region']     ?? ''),
            trim($data['billing_reference']  ?? ''),
            (int)($data['fee_agreed']        ?? 0),
            $sid,
        ]);
    } else {
        db()->prepare(
            "INSERT INTO submission_payment
             (submission_id, billing_email, phone_country_code, phone_number,
              address, city, zip_code, country_region, billing_reference, fee_agreed)
             VALUES (?,?,?,?,?,?,?,?,?,?)"
        )->execute([
            $sid,
            trim($data['billing_email']      ?? ''),
            trim($data['phone_country_code'] ?? ''),
            trim($data['phone_number']       ?? ''),
            trim($data['address']            ?? ''),
            trim($data['city']               ?? ''),
            trim($data['zip_code']           ?? ''),
            trim($data['country_region']     ?? ''),
            trim($data['billing_reference']  ?? ''),
            (int)($data['fee_agreed']        ?? 0),
        ]);
    }

    // Touch submission updated_at
    db()->prepare("UPDATE submissions SET updated_at=NOW() WHERE submission_id=?")
       ->execute([$sid]);

    echo json_encode(['success'=>true]);

} catch(PDOException $e) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}