<?php
session_start();
require_once "config.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$property_id = $_POST['property_id'] ?? '';
$start_date = $_POST['start_date'] ?? '';
$end_date = $_POST['end_date'] ?? '';
$location = $_POST['location'] ?? '';
$total_cost = $_POST['total_cost'] ?? '';
$terms = $_POST['terms'] ?? '';

if (!$property_id || !$start_date || !$end_date || !$location || !$total_cost || !$terms) {
    $_SESSION['advert_error'] = 'All fields required and terms must be agreed';
    header("Location: agent_dash.php");
    exit;
}

$total_cost = floatval($total_cost);
$currency = "NGN"; // adjust if you support multiple currencies

$conn->begin_transaction();

try {
    // Check agent balance
    $stmt = $conn->prepare("SELECT balance FROM users WHERE id=? FOR UPDATE");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows === 0) throw new Exception("Agent not found");
    $agent_balance = floatval($res->fetch_assoc()['balance']);
    $stmt->close();

    if ($agent_balance < $total_cost) {
        throw new Exception("Insufficient balance to create advert");
    }

    // Deduct agent balance
    $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
    $stmt->bind_param("di", $total_cost, $user_id);
    if (!$stmt->execute()) throw new Exception("Failed to deduct agent balance");
    $stmt->close();

   // Log agent transaction (debit)
$ref = uniqid("txn_");
$stmt = $conn->prepare("INSERT INTO transactions (user_id, type, amount, currency, description, reference, status) 
                        VALUES (?, 'debit', ?, ?, 'advert created', ?, 'completed')");
$stmt->bind_param("idss", $user_id, $total_cost, $currency, $ref);
if (!$stmt->execute()) throw new Exception("Failed to log agent transaction");
$stmt->close();


    // Credit admin (ID = 1)
    $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = 1");
    $stmt->bind_param("d", $total_cost);
    if (!$stmt->execute()) throw new Exception("Failed to credit admin balance");
    $stmt->close();

    // Log admin transaction (credit)
$ref2 = uniqid("txn_");
$stmt = $conn->prepare("INSERT INTO transactions (user_id, type, amount, currency, description, reference, status) 
                        VALUES (1, 'credit', ?, ?, 'advert created', ?, 'completed')");
$stmt->bind_param("dss", $total_cost, $currency, $ref2);
if (!$stmt->execute()) throw new Exception("Failed to log admin transaction");
$stmt->close();


    // Insert advert
    $stmt = $conn->prepare("INSERT INTO adverts (property_id, user_id, location, start_date, end_date, status) VALUES (?, ?, ?, ?, ?, 'active')");
    $stmt->bind_param("iisss", $property_id, $user_id, $location, $start_date, $end_date);
    if (!$stmt->execute()) throw new Exception("Failed to create advert");
    $stmt->close();

    $conn->commit();

    $_SESSION['advert_success'] = "Advert created successfully!";
    header("Location: agent_dash.php");
    exit;

} catch (Exception $e) {
    $conn->rollback();
    $_SESSION['advert_error'] = $e->getMessage();
    header("Location: agent_dash.php");
    exit;
}
?>
