<?php
require_once '../includes/constants.php';
require_once '../includes/session.php';
require_once '../includes/functions.php';

if (!isset($_SESSION['admin_id']) || !in_array($_SESSION['admin_role'], ['manager','superadmin'])) {
    die("Access denied");
}

$offerId = $_GET['id'] ?? 0;
$userId = $_SESSION['user_id'] ?? 0;
if (!$offerId || !$userId) die("Missing offer ID or user session");

$targetDir = '../uploads/offer_contracts/';
$allowedTypes = ['pdf','doc','docx','jpg','jpeg','png'];
$maxSize = 10 * 1024 * 1024;

// Handle deletion
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $stmt = $pdo->prepare("SELECT file_path FROM partners_offer_contracts WHERE id = ?");
    $stmt->execute([$_GET['delete']]);
    $file = $stmt->fetch();
    if ($file && file_exists($file['file_path'])) unlink($file['file_path']);
    $pdo->prepare("DELETE FROM partners_offer_contracts WHERE id = ?")->execute([$_GET['delete']]);
    echo "<p class='success'>🗑️ Contract deleted.</p>";
}

// Handle upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['contract_file'])) {
    $type = $_POST['contract_type'];
    $status = $_POST['status'];
    $notes = $_POST['notes'];
    $file = $_FILES['contract_file'];

    $fileName = basename($file['name']);
    $targetPath = $targetDir . $fileName;
    $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowedTypes)) {
        echo "<p class='error'>❌ Invalid file type.</p>";
    } elseif ($file['size'] > $maxSize) {
        echo "<p class='error'>❌ File too large. Max 10MB.</p>";
    } elseif (move_uploaded_file($file['tmp_name'], $targetPath)) {
        $stmt = $pdo->prepare("INSERT INTO partners_offer_contracts 
            (offer_id, contract_type, file_name, file_path, status, notes, uploaded_by)
            VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$offerId, $type, $fileName, $targetPath, $status, $notes, $userId]);
        echo "<p class='success'>✅ Contract uploaded successfully.</p>";
    } else {
        echo "<p class='error'>❌ Upload failed.</p>";
    }
}

// Fetch contracts
$stmt = $pdo->prepare("SELECT c.*, u.username FROM partners_offer_contracts c 
                       JOIN users u ON c.uploaded_by = u.id 
                       WHERE c.offer_id = ? ORDER BY c.created_at DESC");
$stmt->execute([$offerId]);
$contracts = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Contracts'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>📄 Upload Contract for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post" enctype="multipart/form-data">
    <label>Contract Type:
        <select name="contract_type">
            <option value="insertion_order">Insertion Order</option>
            <option value="nda">NDA</option>
            <option value="terms">Terms & Conditions</option>
            <option value="other">Other</option>
        </select>
    </label><br>
    <label>Status:
        <select name="status">
            <option value="pending">Pending</option>
            <option value="signed">Signed</option>
            <option value="expired">Expired</option>
            <option value="rejected">Rejected</option>
        </select>
    </label><br>
    <label>File:
        <input type="file" name="contract_file" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png" required>
    </label><br>
    <label>Notes:<br>
        <textarea name="notes" placeholder="Notes (optional)"></textarea>
    </label><br>
    <button type="submit">Upload Contract</button>
</form>

<hr><h3>📋 Uploaded Contracts</h3>
<table><tr>
    <th>Type</th><th>Status</th><th>Name</th><th>Notes</th><th>Uploader</th><th>Time</th><th>Actions</th>
</tr>
<?php
foreach ($contracts as $c) {
    $link = str_replace('../', '', $c['file_path']);
    echo "<tr>
        <td>" . htmlspecialchars($c['contract_type']) . "</td>
        <td>" . htmlspecialchars($c['status']) . "</td>
        <td>" . htmlspecialchars($c['file_name']) . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($c['notes']) . "</textarea></td>
        <td>" . htmlspecialchars($c['username']) . "</td>
        <td>{$c['created_at']}</td>
        <td>
            <a href='/" . htmlspecialchars($link) . "' target='_blank'>Download</a> | 
            <a href='?id=" . htmlspecialchars($offerId) . "&delete=" . htmlspecialchars($c['id']) . "' onclick='return confirm(\"Delete this contract?\")'>Delete</a>
        </td>
    </tr>";
}
?>
</table>
</div>
</body>
</html>