<?php
include 'auth.php';
include 'db.php';
include 'adminhead.php';
include 'sidebar.php';

$success = "";
$error = "";

/* -------------------------
   DELETE OFFER
---------------------------*/
if (isset($_GET['delete_id'])) {
    $id = intval($_GET['delete_id']);

    // Get existing media
    $stmtFile = $conn->prepare("SELECT media FROM offers WHERE id=?");
    $stmtFile->bind_param("i", $id);
    $stmtFile->execute();
    $fileRow = $stmtFile->get_result()->fetch_assoc();

    // Delete DB record
    $stmt = $conn->prepare("DELETE FROM offers WHERE id=?");
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        $uploadDir = "assets/images/";
        if (!empty($fileRow['media']) && file_exists($uploadDir . $fileRow['media'])) {
            unlink($uploadDir . $fileRow['media']);
        }
        $success = "Offer deleted successfully!";
    } else {
        $error = "Failed to delete offer: " . $stmt->error;
    }
}

/* -------------------------
   ADD OFFER
---------------------------*/
if (isset($_POST['add_offer'])) {
    $title = $_POST['title'];
    $description = $_POST['description'];
    $valid_until = $_POST['valid_until'];
    $mediaFile = NULL;

    $uploadDir = "assets/images/";
    if (!empty($_FILES['media']['name'])) {
        $filename = time() . "_" . basename($_FILES['media']['name']);
        $target = $uploadDir . $filename;
        if (move_uploaded_file($_FILES['media']['tmp_name'], $target)) {
            $mediaFile = $filename;
        }
    }

    $stmt = $conn->prepare("INSERT INTO offers (title, description, media, valid_until) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $title, $description, $mediaFile, $valid_until);
    $success = $stmt->execute() ? "Offer added successfully!" : "Failed to add offer: " . $stmt->error;
}

/* -------------------------
   UPDATE OFFER
---------------------------*/
if (isset($_POST['update_offer'])) {
    $id = intval($_POST['id']);
    $title = $_POST['title'];
    $description = $_POST['description'];
    $valid_until = $_POST['valid_until'];

    // Get old media
    $stmtOld = $conn->prepare("SELECT media FROM offers WHERE id=?");
    $stmtOld->bind_param("i", $id);
    $stmtOld->execute();
    $oldFile = $stmtOld->get_result()->fetch_assoc();
    $mediaFile = $oldFile['media'];

    $uploadDir = "assets/images/";
    if (!empty($_FILES['media']['name'])) {
        $filename = time() . "_" . basename($_FILES['media']['name']);
        $target = $uploadDir . $filename;
        if (move_uploaded_file($_FILES['media']['tmp_name'], $target)) {
            if (!empty($oldFile['media']) && file_exists($uploadDir . $oldFile['media'])) {
                unlink($uploadDir . $oldFile['media']);
            }
            $mediaFile = $filename;
        }
    }

    $stmt = $conn->prepare("UPDATE offers SET title=?, description=?, media=?, valid_until=? WHERE id=?");
    $stmt->bind_param("ssssi", $title, $description, $mediaFile, $valid_until, $id);
    $success = $stmt->execute() ? "Offer updated successfully!" : "Failed to update offer: " . $stmt->error;
}

/* -------------------------
   FETCH ALL OFFERS
---------------------------*/
$data = $conn->query("SELECT * FROM offers ORDER BY id DESC");
?>

<div class="page-wrapper">
    <div class="container-fluid">

        <h3 class="mb-4 fw-bold">Manage Offers</h3>

        <?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>
        <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>

        <!-- ADD OFFER FORM -->
        <div class="card mb-4">
            <div class="card-header">Add New Offer</div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Offer Title</label>
                            <input type="text" name="title" class="form-control" required>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label>Valid Until</label>
                            <input type="date" name="valid_until" class="form-control" required>
                        </div>

                        <div class="col-md-12 mb-3">
                            <label>Description</label>
                            <textarea name="description" class="form-control" rows="3" required></textarea>
                        </div>

                        <div class="col-md-12 mb-3">
                            <label>Upload Image / Video</label>
                            <input type="file" name="media" class="form-control" required>
                        </div>
                    </div>

                    <button type="submit" name="add_offer" class="btn btn-primary">Add Offer</button>
                </form>
            </div>
        </div>

        <!-- OFFERS TABLE -->
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Media</th>
                        <th>Title</th>
                        <th>Description</th>
                        <th>Valid Until</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $i=1; while($row=$data->fetch_assoc()): ?>
                    <tr>
                        <td><?= $i++ ?></td>
                        <td>
                            <?php if ($row['media']): 
                                $ext = pathinfo($row['media'], PATHINFO_EXTENSION);
                                if (in_array(strtolower($ext), ['jpg','jpeg','png','gif'])): ?>
                                    <img src="assets/images/<?= $row['media'] ?>" width="80">
                                <?php else: ?>
                                    <video width="120" controls>
                                        <source src="assets/images/<?= $row['media'] ?>">
                                    </video>
                                <?php endif; 
                            endif; ?>
                        </td>
                        <td><?= htmlspecialchars($row['title']) ?></td>
                        <td><?= htmlspecialchars(substr($row['description'],0,50)) ?>...</td>
                        <td><?= $row['valid_until'] ?></td>
                        <td>
                            <button class="btn btn-warning btn-sm" data-toggle="modal" data-target="#edit<?= $row['id'] ?>">Edit</button>
                            <a href="?delete_id=<?= $row['id'] ?>" onclick="return confirm('Delete this offer?')" class="btn btn-danger btn-sm">Delete</a>
                        </td>
                    </tr>

                    <!-- EDIT MODAL -->
                    <div class="modal fade" id="edit<?= $row['id'] ?>" tabindex="-1">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <form method="POST" enctype="multipart/form-data">
                                    <div class="modal-header">
                                        <h5>Edit Offer #<?= $row['id'] ?></h5>
                                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                                    </div>
                                    <div class="modal-body">
                                        <input type="hidden" name="id" value="<?= $row['id'] ?>">

                                        <div class="form-group">
                                            <label>Title</label>
                                            <input type="text" class="form-control" name="title" value="<?= htmlspecialchars($row['title']) ?>" required>
                                        </div>

                                        <div class="form-group">
                                            <label>Valid Until</label>
                                            <input type="date" class="form-control" name="valid_until" value="<?= $row['valid_until'] ?>" required>
                                        </div>

                                        <div class="form-group">
                                            <label>Description</label>
                                            <textarea class="form-control" name="description" rows="3" required><?= htmlspecialchars($row['description']) ?></textarea>
                                        </div>

                                        <div class="form-group">
                                            <label>Replace Media</label>
                                            <input type="file" name="media" class="form-control">
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" name="update_offer" class="btn btn-success">Save Changes</button>
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>

    </div>
</div>

<?php include 'adminfoot.php'; ?>
