<?php
require_once __DIR__ . '/../../classes/RenewalReminder.php';
require_once __DIR__ . '/../../classes/Logger.php';
include '../../includes/header.php';

$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
$reminderService = new RenewalReminder($conn, $logger);
$isAdmin = $auth->isSuperAdmin($_SESSION['user_id']) || $auth->isWarehousePersonnel($_SESSION['user_id']);
$branchId = $isAdmin ? null : $auth->getUserBranch($_SESSION['user_id']);
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    $title = trim($_POST['title'] ?? '');
    $dueDate = trim($_POST['due_date'] ?? '');
    if ($title === '' || $dueDate === '') {
        $error = 'Title and due date are required.';
    } else {
        $reminderService->createManual([
            'source_type' => $_POST['source_type'] ?? 'subscription',
            'title' => $title,
            'customer_name' => trim($_POST['customer_name'] ?? ''),
            'customer_phone' => trim($_POST['customer_phone'] ?? ''),
            'branch_id' => $branchId,
            'due_date' => $dueDate,
            'reminder_days' => (int)($_POST['reminder_days'] ?? 30),
            'notes' => trim($_POST['notes'] ?? ''),
            'created_by' => $_SESSION['user_id']
        ]);
        header('Location: index.php?success=' . urlencode('Reminder created.'));
        exit;
    }
}

$reminders = $reminderService->getReminders($branchId);
?>

<div class="container mt-4 mb-5">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h2 class="mb-1">Renewal Reminders</h2>
            <p class="text-muted mb-0">Track subscriptions, warranties, and software license renewals.</p>
        </div>
        <div>
            <a href="run.php?action=import_warranties" class="btn btn-outline-primary">Import Warranties</a>
            <a href="run.php?action=send_due" class="btn btn-primary">Send Due Alerts</a>
        </div>
    </div>

    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($_GET['success']); ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <div class="card mb-4">
        <div class="card-header"><strong>Add Subscription or License</strong></div>
        <div class="card-body">
            <form method="POST" class="row g-3">
                <input type="hidden" name="action" value="create">
                <div class="col-md-3">
                    <label class="form-label">Type</label>
                    <select name="source_type" class="form-select">
                        <option value="subscription">Subscription</option>
                        <option value="software_license">Software License</option>
                    </select>
                </div>
                <div class="col-md-5">
                    <label class="form-label">Title</label>
                    <input type="text" name="title" class="form-control" required>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Due Date</label>
                    <input type="date" name="due_date" class="form-control" required>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Alert Days</label>
                    <input type="number" name="reminder_days" class="form-control" min="1" value="30">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Customer or Account</label>
                    <input type="text" name="customer_name" class="form-control">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Phone or Contact</label>
                    <input type="text" name="customer_phone" class="form-control">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Notes</label>
                    <input type="text" name="notes" class="form-control">
                </div>
                <div class="col-12">
                    <button class="btn btn-primary">Save Reminder</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-body table-responsive">
            <table class="table table-striped align-middle" id="remindersTable">
                <thead>
                    <tr>
                        <th>Type</th>
                        <th>Title</th>
                        <th>Customer</th>
                        <th>Branch</th>
                        <th>Due Date</th>
                        <th>Status</th>
                        <th>Contact</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($reminders as $reminder): ?>
                        <tr>
                            <td><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $reminder['source_type']))); ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($reminder['title']); ?></strong><br>
                                <small class="text-muted"><?php echo htmlspecialchars($reminder['notes'] ?? ''); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($reminder['customer_name'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($reminder['branch_name'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($reminder['due_date']); ?></td>
                            <td><span class="badge bg-secondary"><?php echo htmlspecialchars(ucfirst($reminder['status'])); ?></span></td>
                            <td><?php echo htmlspecialchars($reminder['customer_phone'] ?? ''); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    new DataTable('#remindersTable');
</script>

<?php include '../../includes/footer.php'; ?>
