<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once "../php/db_connect.php";

$current_user_id = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
$request_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($current_user_id <= 0) {
    echo "<script>
        alert('Unauthorized access.');
        window.location.href = 'index.php';
    </script>";
    exit;
}

if ($request_id <= 0) {
    echo "<script>
        alert('Invalid request.');
        window.location.href = 'admin.php?page=outsourcing-requests';
    </script>";
    exit;
}

/*
|--------------------------------------------------------------------------
| GET REQUEST DETAILS
|--------------------------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT 
        r.id,
        r.request_code,
        r.target_shop_id,
        r.requester_shop_id,
        r.order_id,
        r.required_date,
        r.status,
        u.shop_name AS requester_shop_name,
        o.order_code
    FROM outsourcing_requests r
    LEFT JOIN users u ON r.requester_shop_id = u.id
    LEFT JOIN orders o ON r.order_id = o.id
    WHERE r.id = ?
      AND r.target_shop_id = ?
    LIMIT 1
");

if (!$stmt) {
    die("Prepare failed: " . $conn->error);
}

$stmt->bind_param("ii", $request_id, $current_user_id);
$stmt->execute();
$res = $stmt->get_result();

if (!$res || $res->num_rows === 0) {
    echo "<script>
        alert('Request not found.');
        window.location.href = 'admin.php?page=outsourcing-requests';
    </script>";
    exit;
}

$request = $res->fetch_assoc();

/*
|--------------------------------------------------------------------------
| CHECK IF CONTRACT ALREADY ACCEPTED
|--------------------------------------------------------------------------
*/
$checkStmt = $conn->prepare("
    SELECT id
    FROM outsourcing_contract_acceptances
    WHERE outsourcing_request_id = ?
    LIMIT 1
");

$checkStmt->bind_param("i", $request_id);
$checkStmt->execute();
$checkRes = $checkStmt->get_result();

if ($checkRes && $checkRes->num_rows > 0) {
    echo "<script>
        alert('You already accepted the binding contract.');
        window.location.href = 'admin.php?page=view-incoming-outsourcing-request&id={$request_id}';
    </script>";
    exit;
}

function h($value) {
    return htmlspecialchars($value ?? "", ENT_QUOTES, "UTF-8");
}

$contract_text = "By accepting this request, the subcontracted shop agrees to complete the job according to the required specifications, agreed timeline, quality standards, and submitted quotation. Failure to meet agreed deliverables may result in cancellation or further administrative review.";
?>

<div class="contract-page">

    <div class="contract-backdrop"></div>

    <div class="contract-modal-box">

        <div class="contract-header">
            <div>
                <h2>Binding Contract Agreement</h2>
                <p>Please review and accept the contract before responding to this outsourcing request.</p>
            </div>

            <a 
                href="admin.php?page=view-incoming-outsourcing-request&id=<?php echo (int)$request_id; ?>" 
                class="contract-close"
            >
                ×
            </a>
        </div>

        <div class="request-summary">
            <div>
                <small>Request Code</small>
                <strong><?php echo h($request['request_code']); ?></strong>
            </div>

            <div>
                <small>From Shop</small>
                <strong><?php echo h($request['requester_shop_name'] ?: 'N/A'); ?></strong>
            </div>

            <div>
                <small>Order Code</small>
                <strong><?php echo h($request['order_code'] ?: 'N/A'); ?></strong>
            </div>
        </div>

        <form action="save_outsourcing_contract.php" method="POST" class="contract-form">
            <input type="hidden" name="request_id" value="<?php echo (int)$request_id; ?>">

            <div class="mb-3">
                <label class="form-label fw-semibold">Contract Terms</label>
                <textarea 
                    name="contract_text" 
                    rows="8" 
                    class="form-control contract-textarea" 
                    readonly
                ><?php echo h($contract_text); ?></textarea>
            </div>

            <div class="contract-check">
                <input 
                    type="checkbox" 
                    id="agreeCheck" 
                    name="agree_contract" 
                    value="1" 
                    required
                >

                <label for="agreeCheck">
                    I have read and agree to the binding contract.
                </label>
            </div>

            <div class="contract-actions">
                <a 
                    href="admin.php?page=view-incoming-outsourcing-request&id=<?php echo (int)$request_id; ?>" 
                    class="btn btn-light border px-4"
                >
                    Cancel
                </a>

                <button type="submit" class="btn btn-success px-4" id="acceptBtn" disabled>
                    Accept Contract
                </button>
            </div>
        </form>

    </div>

</div>

<style>
.contract-page {
    min-height: 70vh;
    position: relative;
}

.contract-backdrop {
    position: fixed;
    inset: 0;
    background: rgba(17, 24, 39, 0.55);
    z-index: 1040;
}

.contract-modal-box {
    position: fixed;
    top: 50%;
    left: 50%;
    width: min(620px, calc(100% - 32px));
    transform: translate(-50%, -50%);
    background: #fff;
    border-radius: 22px;
    padding: 28px;
    z-index: 1050;
    box-shadow: 0 24px 70px rgba(0, 0, 0, 0.25);
    animation: contractPop 0.2s ease;
}

@keyframes contractPop {
    from {
        opacity: 0;
        transform: translate(-50%, -48%) scale(0.96);
    }
    to {
        opacity: 1;
        transform: translate(-50%, -50%) scale(1);
    }
}

.contract-header {
    display: flex;
    justify-content: space-between;
    gap: 16px;
    align-items: flex-start;
    margin-bottom: 18px;
}

.contract-header h2 {
    margin: 0 0 6px;
    font-size: 28px;
    font-weight: 800;
    color: #111827;
}

.contract-header p {
    margin: 0;
    color: #6b7280;
}

.contract-close {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    text-decoration: none;
    color: #374151;
    display: grid;
    place-items: center;
    font-size: 28px;
    line-height: 1;
}

.contract-close:hover {
    background: #f3f4f6;
    color: #111827;
}

.request-summary {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    margin-bottom: 18px;
}

.request-summary div {
    background: #f8fafc;
    border: 1px solid #eef2f7;
    border-radius: 14px;
    padding: 14px;
}

.request-summary small {
    display: block;
    color: #6b7280;
    font-size: 12px;
    margin-bottom: 4px;
}

.request-summary strong {
    color: #111827;
    font-size: 14px;
}

.contract-textarea {
    resize: none;
    border-radius: 14px;
    padding: 14px;
    background: #f9fafb;
}

.contract-check {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    margin: 18px 0;
}

.contract-check input {
    width: 18px;
    height: 18px;
    margin-top: 3px;
}

.contract-check label {
    color: #374151;
    cursor: pointer;
}

.contract-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    flex-wrap: wrap;
}

@media (max-width: 768px) {
    .contract-modal-box {
        padding: 22px;
    }

    .contract-header h2 {
        font-size: 24px;
    }

    .request-summary {
        grid-template-columns: 1fr;
    }

    .contract-actions {
        flex-direction: column-reverse;
    }

    .contract-actions .btn {
        width: 100%;
    }
}
</style>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const agreeCheck = document.getElementById("agreeCheck");
    const acceptBtn = document.getElementById("acceptBtn");

    agreeCheck.addEventListener("change", function () {
        acceptBtn.disabled = !this.checked;
    });
});
</script>