<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../../includes/auth.php';
requirePermission('submit_network_quote');

$BASE = app_base_path();
$userId = $_SESSION['user_id'];

$jobId = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($jobId <= 0) {
    header("Location: " . $BASE . "/installer/network/invites.php");
    exit;
}

/* ===============================
   VERIFY INVITE EXISTS
=================================*/
$inviteStmt = $pdo->prepare("
    SELECT *
    FROM network_job_invites
    WHERE job_id = ?
    AND installer_user_id = ?
    AND status = 'INVITED'
");
$inviteStmt->execute([$jobId, $userId]);
$invite = $inviteStmt->fetch(PDO::FETCH_ASSOC);

if (!$invite) {
    die("No active invite found.");
}

/* ===============================
   FETCH JOB (LIMITED VIEW)
=================================*/
$stmt = $pdo->prepare("
    SELECT id, title, category, suburb, city, description
    FROM network_jobs
    WHERE id = ?
");
$stmt->execute([$jobId]);
$job = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$job) {
    die("Job not found.");
}

/* ===============================
   HANDLE QUOTE SUBMISSION
=================================*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $amount = $_POST['quote_amount'] ?? 0;
    $duration = $_POST['estimated_duration'] ?? 0;
    $notes = $_POST['notes'] ?? '';

    if ($amount > 0) {

        $pdo->beginTransaction();

        $insert = $pdo->prepare("
            INSERT INTO network_job_quotes
            (job_id, installer_user_id, quote_amount, eta_days, notes, status, submitted_at)
            VALUES (?, ?, ?, ?, ?, 'SUBMITTED', NOW())
        ");

        $insert->execute([
            $jobId,
            $userId,
            $amount,
            (int)$duration,
            $notes
        ]);

        // Update invite status
        $pdo->prepare("
            UPDATE network_job_invites
            SET status = 'QUOTED'
            WHERE id = ?
        ")->execute([$invite['id']]);

        // Update job status
        $pdo->prepare("
            UPDATE network_jobs
            SET status = 'QUOTED_TO_CLIENT'
            WHERE id = ?
        ")->execute([$jobId]);

        $pdo->commit();

        header("Location: " . $BASE . "/installer/network/invites.php");
        exit;
    }
}

require_once __DIR__ . '/../../../includes/header.php';
require_once __DIR__ . '/../../../includes/sidebar.php';
?>

<div class="main-content">

    <div class="page-header">
        <h2>Submit Quote — <?= htmlspecialchars($job['title']) ?></h2>
        <p class="page-subtitle">
            Location: <?= htmlspecialchars($job['suburb'] . ', ' . $job['city']) ?>
        </p>
    </div>

    <div class="card">

        <h4>Job Scope</h4>
        <p><strong>Category:</strong> <?= htmlspecialchars($job['category']) ?></p>
        <p><?= nl2br(htmlspecialchars($job['description'])) ?></p>

        <hr>

        <h4>Submit Your Quote</h4>

        <form method="POST">

            <div style="margin-bottom:15px;">
                <label>Quote Amount (R)</label><br>
                <input type="number"
                       step="0.01"
                       name="quote_amount"
                       required
                       class="form-control">
            </div>

            <div style="margin-bottom:15px;">
                <label>Estimated Duration (e.g. 2 days)</label><br>
                <input type="text"
                       name="estimated_duration"
                       class="form-control">
            </div>

            <div style="margin-bottom:15px;">
                <label>Notes</label><br>
                <textarea name="notes"
                          class="form-control"
                          rows="4"></textarea>
            </div>

            <button class="btn-primary">Submit Quote</button>

        </form>

    </div>

</div>

<?php require_once __DIR__ . '/../../../includes/footer.php'; ?>