<?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_creatives/';
$allowedTypes = ['jpg','jpeg','png','gif','zip','html','pdf'];
$maxSize = 10 * 1024 * 1024;

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

// Handle upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['creative_file'])) {
    $type = $_POST['creative_type'];
    $notes = $_POST['notes'];
    $tags = $_POST['tags'];
    $width = $_POST['width'] ?? null;
    $height = $_POST['height'] ?? null;
    $file = $_FILES['creative_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 ($ext === 'zip') {
        $zip = new ZipArchive();
        if ($zip->open($file['tmp_name']) === TRUE) {
            $zip->extractTo($targetDir);
            $zip->close();
            echo "<p class='success'>✅ ZIP unpacked. Files saved to $targetDir</p>";
            foreach (scandir($targetDir) as $f) {
                if (in_array(strtolower(pathinfo($f, PATHINFO_EXTENSION)), ['jpg','jpeg','png','gif','html','pdf'])) {
                    $stmt = $pdo->prepare("INSERT INTO partners_offer_creatives 
                        (offer_id, creative_type, file_name, file_path, uploaded_by) 
                        VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([$offerId, 'banner', $f, $targetDir . $f, $userId]);
                }
            }
        } else {
            echo "<p class='error'>❌ ZIP unpack failed.</p>";
        }
    } elseif (move_uploaded_file($file['tmp_name'], $targetPath)) {
        $stmt = $pdo->prepare("INSERT INTO partners_offer_creatives 
            (offer_id, creative_type, file_name, file_path, width, height, notes, tags, uploaded_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$offerId, $type, $fileName, $targetPath, $width, $height, $notes, $tags, $userId]);
        echo "<p class='success'>✅ Creative uploaded successfully.</p>";
    } else {
        echo "<p class='error'>❌ Upload failed.</p>";
    }
}

// Fetch creatives
$stmt = $pdo->prepare("SELECT c.*, u.username FROM partners_offer_creatives c 
                       JOIN users u ON c.uploaded_by = u.id 
                       WHERE c.offer_id = ? ORDER BY c.created_at DESC");
$stmt->execute([$offerId]);
$creatives = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Offer Creatives'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>🎨 Upload Creative for Offer #<?php echo htmlspecialchars($offerId); ?></h2>
<form method="post" enctype="multipart/form-data">
    <label>Creative Type:
        <select name="creative_type">
            <option value="banner">Banner</option>
            <option value="email">Email Creative</option>
            <option value="preview">Preview Link</option>
            <option value="other">Other</option>
        </select>
    </label><br>
    <label>File:
        <input type="file" name="creative_file" accept=".jpg,.jpeg,.png,.gif,.zip,.html,.pdf" required>
    </label><br>
    <label>Size:
        <input name="width" placeholder="Width (px)"> 
        <input name="height" placeholder="Height (px)">
    </label><br>
    <label>Tags:<br>
        <input name="tags" placeholder="Tags (comma-separated)">
    </label><br>
    <label>Notes:<br>
        <textarea name="notes" placeholder="Notes (optional)"></textarea>
    </label><br>
    <button type="submit">Upload Creative</button>
</form>

<hr><h3>📋 Uploaded Creatives</h3>
<table><tr>
    <th>Type</th><th>Name</th><th>Size</th><th>Tags</th><th>Notes</th><th>Uploader</th><th>Time</th><th>Actions</th>
</tr>
<?php
foreach ($creatives as $c) {
    $link = str_replace('../', '', $c['file_path']);
    $isImage = in_array(strtolower(pathinfo($c['file_name'], PATHINFO_EXTENSION)), ['jpg','jpeg','png','gif']);
    $preview = $isImage ? "<img src='/" . htmlspecialchars($link) . "' width='100'>" : "<a href='/" . htmlspecialchars($link) . "' target='_blank'>Download</a>";
    echo "<tr>
        <td>" . htmlspecialchars($c['creative_type']) . "</td>
        <td>" . htmlspecialchars($c['file_name']) . "</td>
        <td>" . htmlspecialchars($c['width']) . "x" . htmlspecialchars($c['height']) . "</td>
        <td>" . htmlspecialchars($c['tags']) . "</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>
            $preview | 
            <a href='?id=" . htmlspecialchars($offerId) . "&delete=" . htmlspecialchars($c['id']) . "' onclick='return confirm(\"Delete this creative?\")'>Delete</a>
        </td>
    </tr>";
}
?>
</table>
</div>
</body>
</html>