<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION["user_id"]) || !in_array($_SESSION["role"], ["customer","company_admin"])) {
    header("Location: ../auth/login.php");
    exit;
}

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    die("Invalid request.");
}

$customerUserId = $_SESSION["user_id"];
$shopId = $_POST["shop_id"] ?? null;
$amount = floatval($_POST["amount"] ?? 0);

if (!$shopId || $amount <= 0) {
    die("Invalid payment amount.");
}

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare("
        SELECT *
        FROM customers
        WHERE user_id = ?
        LIMIT 1
        FOR UPDATE
    ");
    $stmt->execute([$customerUserId]);
    $customer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$customer) {
        throw new Exception("Customer account not found.");
    }

    if ($customer["status"] !== "active") {
        throw new Exception("Customer account is inactive.");
    }

    if ($customer["balance"] < $amount) {
        throw new Exception("Insufficient balance.");
    }

    $stmt = $pdo->prepare("
        SELECT *
        FROM partner_shops
        WHERE id = ?
        LIMIT 1
        FOR UPDATE
    ");
    $stmt->execute([$shopId]);
    $shop = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$shop) {
        throw new Exception("Shop not found.");
    }

    if ($shop["status"] !== "active") {
        throw new Exception("Shop is inactive.");
    }

    $stmt = $pdo->prepare("
        UPDATE customers
        SET balance = balance - ?
        WHERE id = ?
    ");
    $stmt->execute([$amount, $customer["id"]]);

    $stmt = $pdo->prepare("
        UPDATE partner_shops
        SET credit_balance = credit_balance + ?
        WHERE id = ?
    ");
    $stmt->execute([$amount, $shop["id"]]);

    $transactionCode = "PAY" . date("YmdHis") . rand(1000, 9999);

    $stmt = $pdo->prepare("
        INSERT INTO transactions
        (
            transaction_code,
            from_type,
            from_id,
            to_type,
            to_id,
            amount,
            transaction_type,
            remarks,
            partner_read_at
        )
        VALUES (?, 'customer', ?, 'partner', ?, ?, 'credit_transfer', ?, NULL)
    ");

    $remarks = "Customer payment to shop: " . $shop["shop_name"];

    $stmt->execute([
        $transactionCode,
        $customer["id"],
        $shop["id"],
        $amount,
        $remarks
    ]);

    $pdo->commit();

    header("Location: payment_success.php?tx=" . urlencode($transactionCode));
    exit;

} catch (Exception $e) {
    $pdo->rollBack();
    die($e->getMessage());
}