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

if (!isLoggedIn()) { echo json_encode(['success'=>false,'error'=>'Not authenticated']); exit; }

$action  = $_GET['action'] ?? '';
$userId  = $_SESSION['user_id'];
$isAdmin = !empty($_SESSION['is_admin']);

switch ($action) {

    // ── Get saved billing (user sees own; admin passes user_id param) ──
    case 'get':
        $uid = $isAdmin ? (int)($_GET['user_id'] ?? $userId) : $userId;
        $stmt = db()->prepare("SELECT * FROM saved_billing WHERE user_id=?");
        $stmt->execute([$uid]);
        $row = $stmt->fetch();
        if ($row && !$isAdmin) {
            // Mask card number for non-admin
            $row['card_display'] = $row['card_brand'] && $row['card_last4']
                ? $row['card_brand'] . ' ····' . $row['card_last4']
                : null;
            unset($row['sq_card_id']);
        }
        echo json_encode(['success'=>true, 'billing'=>$row ?: null]);
        break;

    // ── Save / update billing info ─────────────────────────────
    case 'save':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false]); exit; }
        $data = json_decode(file_get_contents('php://input'), true);
        $uid  = $isAdmin && isset($data['user_id']) ? (int)$data['user_id'] : $userId;

        $firstName = substr(trim($data['first_name'] ?? ''), 0, 80);
        $lastName  = substr(trim($data['last_name']  ?? ''), 0, 80);
        $email     = substr(strtolower(trim($data['email'] ?? '')), 0, 150);
        $address   = substr(trim($data['address'] ?? ''), 0, 200);
        $city      = substr(trim($data['city']    ?? ''), 0, 80);
        $state     = strtoupper(substr(trim($data['state'] ?? ''), 0, 2));
        $zip       = substr(trim($data['zip']     ?? ''), 0, 10);

        // Card info — only update if provided
        $cardBrand    = isset($data['card_brand'])    ? substr(trim($data['card_brand']),    0, 30)  : null;
        $cardLast4    = isset($data['card_last4'])    ? substr(trim($data['card_last4']),    0, 4)   : null;
        $cardExpMonth = isset($data['card_exp_month'])? substr(trim($data['card_exp_month']),0, 2)   : null;
        $cardExpYear  = isset($data['card_exp_year']) ? substr(trim($data['card_exp_year']), 0, 4)   : null;
        $sqCardId     = isset($data['sq_card_id'])    ? substr(trim($data['sq_card_id']),    0, 255) : null;

        $stmt = db()->prepare("
            INSERT INTO saved_billing
                (user_id, first_name, last_name, email, address, city, state, zip,
                 card_brand, card_last4, card_exp_month, card_exp_year, sq_card_id)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
            ON DUPLICATE KEY UPDATE
                first_name=VALUES(first_name), last_name=VALUES(last_name),
                email=VALUES(email), address=VALUES(address), city=VALUES(city),
                state=VALUES(state), zip=VALUES(zip),
                card_brand=COALESCE(VALUES(card_brand), card_brand),
                card_last4=COALESCE(VALUES(card_last4), card_last4),
                card_exp_month=COALESCE(VALUES(card_exp_month), card_exp_month),
                card_exp_year=COALESCE(VALUES(card_exp_year), card_exp_year),
                sq_card_id=COALESCE(VALUES(sq_card_id), sq_card_id)
        ");
        $stmt->execute([$uid,$firstName,$lastName,$email,$address,$city,$state,$zip,
                        $cardBrand,$cardLast4,$cardExpMonth,$cardExpYear,$sqCardId]);
        echo json_encode(['success'=>true]);
        break;

    // ── Clear card info only ───────────────────────────────────
    case 'clear_card':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false]); exit; }
        $data = json_decode(file_get_contents('php://input'), true);
        $uid  = $isAdmin && isset($data['user_id']) ? (int)$data['user_id'] : $userId;
        db()->prepare("UPDATE saved_billing SET card_brand=NULL, card_last4=NULL, card_exp_month=NULL, card_exp_year=NULL, sq_card_id=NULL WHERE user_id=?")
             ->execute([$uid]);
        echo json_encode(['success'=>true]);
        break;

    // ── Clear all billing info ────────────────────────────────
    case 'clear_all':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false]); exit; }
        $data = json_decode(file_get_contents('php://input'), true);
        $uid  = $isAdmin && isset($data['user_id']) ? (int)$data['user_id'] : $userId;
        db()->prepare("DELETE FROM saved_billing WHERE user_id=?")->execute([$uid]);
        echo json_encode(['success'=>true]);
        break;

    default:
        echo json_encode(['success'=>false,'error'=>'Unknown action']);
}
