<?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");

// Handle deletion
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $stmt = $pdo->prepare("SELECT file_path FROM partners_offer_files 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_files WHERE id = ?")->execute([$_GET['delete']]);
    echo "<p class='success'>🗑️ File deleted.</p>";
}

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

    $targetDir = '../uploads/offer_files/';
    $fileName = basename($file['name']);
    $targetPath = $targetDir . $fileName;

    // Validation
    $allowedTypes = ['pdf','doc','docx','xls','xlsx','csv','jpg','jpeg','png','zip'];
    $maxSize = 10 * 1024 * 1024; // 10MB
    $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_files (offer_id, file_type, file_name, file_path, uploaded_by, notes)
                               VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$offerId, $type, $fileName, $targetPath, $userId, $notes]);
        echo "<p class='success'>✅ File uploaded successfully.</p>";
    } else {
        echo "<p class='error'>❌ Upload failed.</p>";
    }
}

// Fetch files
$stmt = $pdo->prepare("SELECT f.*, u.username FROM partners_offer_files f 
                       JOIN users u ON f.uploaded_by = u.id 
                       WHERE f.offer_id = ? ORDER BY f.created_at DESC");
$stmt->execute([$offerId]);
$files = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Files'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>📦 Upload Files for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post" enctype="multipart/form-data">
    <label>File Type:
        <select name="file_type">
            <option value="suppression">Suppression File</option>
            <option value="creative">Creative Asset</option>
            <option value="terms">Terms & Conditions</option>
            <option value="insertion_order">Insertion Order</option>
            <option value="other">Other</option>
        </select>
    </label><br>
    <label>File:
        <input type="file" name="offer_file" accept=".pdf,.doc,.docx,.xls,.xlsx,.csv,.jpg,.jpeg,.png,.zip" required>
    </label><br>
    <small>Max size: 10MB. Allowed: PDF, DOC, XLS, CSV, JPG, PNG, ZIP</small><br>
    <label>Notes:<br>
        <textarea name="notes" placeholder="Notes (optional)"></textarea>
    </label><br>
    <button type="submit">Upload File</button>
</form>

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