<?php
/**
 * Booking — providers CRUD + weekly hours editor + service links.
 */
require_once dirname(__DIR__, 3) . '/config.php';
require_once dirname(__DIR__) . '/BookingAPI.php';

Auth::require();
Auth::requirePerm('booking.manage_providers');
BookingAPI::ensureSchema();

$pageTitle  = 'Providers';
$currentNav = 'booking-providers';

$tid    = current_tenant_id();
$flash  = null;
$editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$isNew  = !empty($_GET['new']);

$editing  = null;
$linked   = [];
$hours    = [];
if ($editId > 0) {
    $editing = Database::row("SELECT * FROM booking_providers WHERE id = ? AND tenant_id = ?", [$editId, $tid]);
    if (!$editing) { http_response_code(404); $editId = 0; $editing = null; }
    else {
        $linked = array_column(Database::rows(
            "SELECT service_id FROM booking_provider_services WHERE provider_id = ?", [$editId]
        ), 'service_id');
        $hours = BookingAPI::getProviderHours($editId);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $flash = ['type' => 'error', 'msg' => 'Security check failed.'];
    } else {
        $action = $_POST['_action'] ?? '';
        if ($action === 'save') {
            $id   = (int)($_POST['id'] ?? 0);
            $name = trim((string)($_POST['name'] ?? ''));
            if ($name === '') {
                $flash = ['type' => 'error', 'msg' => 'Name is required.'];
            } else {
                $row = [
                    'tenant_id' => $tid,
                    'name'      => mb_substr($name, 0, 160),
                    'email'     => trim((string)($_POST['email'] ?? '')) !== ''
                                   && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
                                   ? mb_substr(trim($_POST['email']), 0, 200) : null,
                    'timezone'  => mb_substr(trim((string)($_POST['timezone'] ?? 'UTC')), 0, 60),
                    'bio'       => trim((string)($_POST['bio'] ?? '')) ?: null,
                    'is_active' => !empty($_POST['is_active']) ? 1 : 0,
                ];
                if ($id > 0) {
                    Database::update('booking_providers', $row, 'id = ? AND tenant_id = ?', [$id, $tid]);
                    AuditLog::record('booking.provider_updated', (string)$id);
                } else {
                    $id = Database::insert('booking_providers', $row);
                    AuditLog::record('booking.provider_created', (string)$id);
                }

                // Sync linked services
                Database::delete('booking_provider_services', 'provider_id = ?', [$id]);
                $services = $_POST['services'] ?? [];
                if (is_array($services)) {
                    foreach ($services as $sid) {
                        $sid = (int)$sid;
                        if ($sid > 0) {
                            Database::insert('booking_provider_services',
                                ['provider_id' => $id, 'service_id' => $sid]);
                        }
                    }
                }

                // Sync hours — full replace
                Database::delete('booking_provider_hours', 'provider_id = ? AND tenant_id = ?', [$id, $tid]);
                for ($d = 0; $d <= 6; $d++) {
                    $on    = !empty($_POST['day_' . $d . '_on']);
                    $start = (string)($_POST['day_' . $d . '_start'] ?? '');
                    $end   = (string)($_POST['day_' . $d . '_end']   ?? '');
                    if (!$on) continue;
                    if (!preg_match('/^\d{2}:\d{2}$/', $start) || !preg_match('/^\d{2}:\d{2}$/', $end)) continue;
                    if ($end <= $start) continue;
                    Database::insert('booking_provider_hours', [
                        'tenant_id'   => $tid,
                        'provider_id' => $id,
                        'day_of_week' => $d,
                        'start_time'  => $start . ':00',
                        'end_time'    => $end   . ':00',
                    ]);
                }

                $flash = ['type' => 'success', 'msg' => 'Provider saved.'];
                header('Location: ?edit=' . $id);
                exit;
            }
        } elseif ($action === 'delete') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id > 0) {
                Database::delete('booking_provider_services', 'provider_id = ?', [$id]);
                Database::delete('booking_provider_hours',    'provider_id = ? AND tenant_id = ?', [$id, $tid]);
                Database::delete('booking_providers',         'id = ? AND tenant_id = ?', [$id, $tid]);
                AuditLog::record('booking.provider_deleted', (string)$id);
                $flash = ['type' => 'success', 'msg' => 'Provider deleted.'];
                header('Location: ' . plugin_url('booking', 'admin/providers.php'));
                exit;
            }
        }
    }
}

$providers = Database::rows(
    "SELECT * FROM booking_providers WHERE tenant_id = ? ORDER BY name", [$tid]
);
$allServices = Database::rows(
    "SELECT id, name FROM booking_services WHERE tenant_id = ? AND is_active = 1 ORDER BY name", [$tid]
);

// Build hours map for display
$hoursByDay = array_fill(0, 7, null);
foreach ($hours as $h) $hoursByDay[(int)$h['day_of_week']] = $h;

require SLATE_ROOT . '/admin/partials/header.php';

$dayNames = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
?>

<?php slate_breadcrumbs([
    ['label' => __('dashboard', 'Dashboard'), 'href' => SLATE_URL . '/admin/'],
    ['label' => __('booking', 'Booking'), 'href' => plugin_url('booking', 'admin/index.php')],
    ['label' => 'Providers'],
]); ?>

<div class="page-header">
    <div><h1>Providers</h1></div>
    <?php if (!$isNew && !$editing): ?>
        <a href="?new=1" class="btn btn-primary">New provider</a>
    <?php endif; ?>
</div>

<?php if ($flash): ?><div class="alert alert-<?= e($flash['type']) ?>"><?= e($flash['msg']) ?></div><?php endif; ?>

<?php if ($isNew || $editing):
    $p = $editing ?: ['id'=>0,'name'=>'','email'=>'','timezone'=>'UTC','bio'=>'','is_active'=>1];
?>
    <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="_action" value="save">
        <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">

        <?php slate_page_layout('with-aside'); ?>
            <div class="page-main">
                <div class="card">
                    <div class="card-header"><h2><?= $editing ? 'Edit ' . e($editing['name']) : 'New provider' ?></h2></div>
                    <div class="field-row field-row-2">
                        <div class="field">
                            <label class="field-label" for="name">Name <span class="field-required">*</span></label>
                            <input type="text" id="name" name="name" required maxlength="160" value="<?= e($p['name']) ?>">
                        </div>
                        <div class="field">
                            <label class="field-label" for="email">Email</label>
                            <input type="email" id="email" name="email" maxlength="200" value="<?= e($p['email'] ?? '') ?>">
                        </div>
                    </div>
                    <div class="field-row field-row-2">
                        <div class="field">
                            <label class="field-label" for="timezone">Timezone</label>
                            <input type="text" id="timezone" name="timezone" maxlength="60" value="<?= e($p['timezone']) ?>">
                            <div class="field-hint">IANA name (UTC, America/New_York, …). Currently informational only.</div>
                        </div>
                        <div class="field" style="display:flex;align-items:flex-end;">
                            <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                                <input type="checkbox" name="is_active" value="1" <?= !empty($p['is_active']) ? 'checked' : '' ?>>
                                <span>Active (bookable)</span>
                            </label>
                        </div>
                    </div>
                    <div class="field">
                        <label class="field-label" for="bio">Bio</label>
                        <textarea id="bio" name="bio" maxlength="2000"><?= e($p['bio'] ?? '') ?></textarea>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header"><h2>Weekly hours</h2></div>
                    <p class="text-sm text-muted">Tick a day to enable. Times are local to the site's timezone.</p>
                    <?php for ($d = 0; $d <= 6; $d++):
                        $h = $hoursByDay[$d];
                        $on    = (bool)$h;
                        $start = $h ? substr($h['start_time'], 0, 5) : '09:00';
                        $end   = $h ? substr($h['end_time'],   0, 5) : '17:00';
                    ?>
                        <div class="field-row field-row-3" style="align-items:flex-end;">
                            <div class="field">
                                <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                                    <input type="checkbox" name="day_<?= $d ?>_on" value="1" <?= $on ? 'checked' : '' ?>>
                                    <strong><?= e($dayNames[$d]) ?></strong>
                                </label>
                            </div>
                            <div class="field">
                                <input type="time" name="day_<?= $d ?>_start" value="<?= e($start) ?>">
                            </div>
                            <div class="field">
                                <input type="time" name="day_<?= $d ?>_end" value="<?= e($end) ?>">
                            </div>
                        </div>
                    <?php endfor; ?>
                </div>

                <div class="flex gap-2 mt-3">
                    <button type="submit" class="btn btn-primary"><?= $editing ? 'Save changes' : 'Create provider' ?></button>
                    <a href="<?= e(plugin_url('booking', 'admin/providers.php')) ?>" class="btn btn-ghost">Cancel</a>
                </div>
            </div>

            <aside class="page-aside">
                <div class="aside-card">
                    <div class="aside-card-title">Services this provider offers</div>
                    <?php if (!$allServices): ?>
                        <p class="text-sm text-muted">No services yet. <a href="<?= e(plugin_url('booking', 'admin/services.php')) ?>">Create one</a>.</p>
                    <?php else: ?>
                        <div style="display:flex;flex-direction:column;gap:6px;">
                            <?php foreach ($allServices as $s): ?>
                                <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                                    <input type="checkbox" name="services[]" value="<?= (int)$s['id'] ?>"
                                           <?= in_array((int)$s['id'], $linked, true) ? 'checked' : '' ?>>
                                    <span><?= e($s['name']) ?></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </aside>
        <?php slate_page_layout_end(); ?>
    </form>
<?php endif; ?>

<?php if (!$providers): ?>
    <div class="card"><div class="empty"><div class="empty-title">No providers yet</div></div></div>
<?php else: ?>
    <div class="data-list" data-single-open>
        <?php foreach ($providers as $p):
            $svcCount = (int) Database::value(
                "SELECT COUNT(*) FROM booking_provider_services WHERE provider_id = ?", [$p['id']]);
            $hrCount = (int) Database::value(
                "SELECT COUNT(*) FROM booking_provider_hours WHERE provider_id = ?", [$p['id']]);

            $detail = [
                'Email'    => $p['email'] ?: '—',
                'Timezone' => $p['timezone'],
                'Services' => $svcCount,
                'Hours'    => $hrCount . ' day(s) of the week',
            ];
            if (!empty($p['bio'])) $detail['Bio'] = ['label'=>'Bio','value'=>$p['bio'],'muted'=>true];

            $actions = '<a href="?edit=' . (int)$p['id'] . '" class="btn btn-sm">Edit</a> '
                     . '<form method="post" style="display:inline;margin:0;" onsubmit="return confirm(\'Delete this provider?\')">'
                     . csrf_field()
                     . '<input type="hidden" name="_action" value="delete">'
                     . '<input type="hidden" name="id" value="' . (int)$p['id'] . '">'
                     . '<button class="btn btn-sm btn-danger">Delete</button></form>';

            slate_data_row([
                'avatar'       => mb_substr($p['name'], 0, 2),
                'avatar_color' => $p['is_active'] ? 'accent' : 'muted',
                'title'        => $p['name'],
                'meta'         => $p['email'] ?: $p['timezone'],
                'badge'        => $p['is_active'] ? ['Active', 'active'] : ['Inactive', 'inactive'],
                'detail'       => $detail,
                'actions'      => $actions,
            ]);
        endforeach; ?>
    </div>
    <?php slate_data_list_script(); ?>
<?php endif; ?>

<?php require SLATE_ROOT . '/admin/partials/footer.php'; ?>
