<?php
session_start();

// ALL ACTIONS THAT REDIRECT must run BEFORE any output (before header.php)
include_once("config/db.php");
$uid = (int)$_SESSION['user_id'];
$action = $_GET['action'] ?? $_POST['action'] ?? '';

// TOGGLE STATUS
if ($action === 'toggle' && isset($_GET['id'])) {
    $rid  = (int)$_GET['id'];
    $stmt = $conn->prepare("UPDATE restaurants SET status = 1 - status WHERE id=?");
    $stmt->bind_param("i", $rid); $stmt->execute();
    header("Location: restaurants.php?msg=toggled"); exit;
}

// DELETE
if ($action === 'delete' && isset($_POST['id'])) {
    $rid = (int)$_POST['id'];
    $conn->begin_transaction();
    try {
        $conn->query("DELETE wt FROM wallet_transactions wt INNER JOIN orders o ON wt.order_id=o.id WHERE o.restaurant_id={$rid}");
        $conn->query("DELETE FROM orders WHERE restaurant_id={$rid}");
        $conn->query("DELETE FROM menu_items WHERE restaurant_id={$rid}");
        $conn->query("DELETE FROM categories WHERE restaurant_id={$rid}");
        $conn->query("DELETE FROM restaurant_tables WHERE restaurant_id={$rid}");
        $conn->query("DELETE FROM staff_shifts WHERE restaurant_id={$rid}");
        $conn->query("DELETE FROM notifications WHERE restaurant_id={$rid}");
        $conn->query("DELETE FROM qr_scans WHERE restaurant_id={$rid}");
        $conn->query("DELETE FROM wallets WHERE restaurant_id={$rid} AND wallet_type='restaurant'");
        $conn->query("UPDATE users SET restaurant_id=NULL WHERE restaurant_id={$rid}");
        $stmt = $conn->prepare("DELETE FROM restaurants WHERE id=?");
        $stmt->bind_param("i", $rid); $stmt->execute();
        $conn->commit();
        header("Location: restaurants.php?msg=deleted"); exit;
    } catch (Exception $e) {
        $conn->rollback();
        header("Location: restaurants.php?msg=delete_failed"); exit;
    }
}

// CREATE / EDIT
$success = $error = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($action, ['create', 'edit'])) {
    $name        = trim($_POST['name']        ?? '');
    $email       = trim($_POST['email']       ?? '');
    $phone       = trim($_POST['phone']       ?? '');
    $address     = trim($_POST['address']     ?? '');
    $description = trim($_POST['description'] ?? '');
    $rid_edit    = (int)($_POST['restaurant_id'] ?? 0);
    $admin_name  = trim($_POST['admin_name']  ?? '');
    $admin_email = trim($_POST['admin_email'] ?? '');
    $admin_phone = trim($_POST['admin_phone'] ?? '');
    $admin_pw    = $_POST['admin_password']   ?? '';

    if (!$name || !$email) {
        $error = "Restaurant name and email are required.";
    } else {
        $conn->begin_transaction();
        try {
            if ($action === 'create') {
                $rs = $conn->prepare("INSERT INTO restaurants (name,email,phone,address,description,status,created_by) VALUES (?,?,?,?,?,1,?)");
                $rs->bind_param("sssssi", $name, $email, $phone, $address, $description, $uid);
                $rs->execute();
                $new_rid = $conn->insert_id;

                $wchk = $conn->prepare("SELECT id FROM wallets WHERE restaurant_id=? AND wallet_type='restaurant' LIMIT 1");
                $wchk->bind_param("i", $new_rid); $wchk->execute();
                if ($wchk->get_result()->num_rows === 0) {
                    $wins = $conn->prepare("INSERT INTO wallets (user_id, wallet_type, restaurant_id, balance) VALUES (?, 'restaurant', ?, 0.00)");
                    $wins->bind_param("ii", $new_rid, $new_rid); $wins->execute();
                }

                if ($admin_name && $admin_email && $admin_pw) {
                    $echk = $conn->prepare("SELECT id FROM users WHERE email=?");
                    $echk->bind_param("s", $admin_email); $echk->execute();
                    if ($echk->get_result()->num_rows > 0) throw new Exception("Admin email '{$admin_email}' is already in use.");
                    $hash = password_hash($admin_pw, PASSWORD_DEFAULT);
                    $us   = $conn->prepare("INSERT INTO users (restaurant_id,name,email,phone,password,role,status) VALUES (?,?,?,?,?,'restaurant_admin',1)");
                    $us->bind_param("issss", $new_rid, $admin_name, $admin_email, $admin_phone, $hash); $us->execute();
                }
                $conn->commit();
                header("Location: restaurants.php?msg=created&rname=" . urlencode($name)); exit;

            } else {
                $rs = $conn->prepare("UPDATE restaurants SET name=?,email=?,phone=?,address=?,description=? WHERE id=?");
                $rs->bind_param("sssssi", $name, $email, $phone, $address, $description, $rid_edit); $rs->execute();

                $wchk = $conn->prepare("SELECT id FROM wallets WHERE restaurant_id=? AND wallet_type='restaurant' LIMIT 1");
                $wchk->bind_param("i", $rid_edit); $wchk->execute();
                if ($wchk->get_result()->num_rows === 0) {
                    $wins = $conn->prepare("INSERT INTO wallets (user_id, wallet_type, restaurant_id, balance) VALUES (?, 'restaurant', ?, 0.00)");
                    $wins->bind_param("ii", $rid_edit, $rid_edit); $wins->execute();
                }
                if ($admin_pw) {
                    $hash = password_hash($admin_pw, PASSWORD_DEFAULT);
                    $up   = $conn->prepare("UPDATE users SET password=? WHERE restaurant_id=? AND role='restaurant_admin'");
                    $up->bind_param("si", $hash, $rid_edit); $up->execute();
                }
                $conn->commit();
                header("Location: restaurants.php?msg=updated"); exit;
            }
        } catch (Exception $e) {
            $conn->rollback();
            $error = "Operation failed: " . $e->getMessage();
        }
    }
}

// Safe to output HTML now
$page_title = 'Restaurants';
$active_nav = 'restaurants';
include("includes/header.php");

$msg = $_GET['msg'] ?? '';
if ($msg === 'created')       $success = "Restaurant '" . htmlspecialchars($_GET['rname'] ?? '') . "' created with its Dabil wallet!";
if ($msg === 'updated')       $success = "Restaurant updated successfully!";
if ($msg === 'toggled')       $success = "Restaurant status updated.";
if ($msg === 'deleted')       $success = "Restaurant deleted successfully.";
if ($msg === 'delete_failed') $error   = "Could not delete restaurant. Please try again.";

$edit_restaurant = null;
if ($action === 'edit' && isset($_GET['id'])) {
    $rid = (int)$_GET['id'];
    $rs  = $conn->prepare("SELECT * FROM restaurants WHERE id=?");
    $rs->bind_param("i", $rid); $rs->execute();
    $edit_restaurant = $rs->get_result()->fetch_assoc();
}

$search = trim($_GET['search'] ?? '');
$filter = $_GET['filter'] ?? 'all';
$query  = "SELECT r.*, u.name as admin_name, u.email as admin_email,
           (SELECT COUNT(*) FROM orders o WHERE o.restaurant_id=r.id) as order_count,
           (SELECT COUNT(*) FROM menu_items m WHERE m.restaurant_id=r.id AND m.is_available=1) as menu_count,
           COALESCE((SELECT w.balance FROM wallets w WHERE w.restaurant_id=r.id AND w.wallet_type='restaurant' LIMIT 1),0) as wallet_balance
          FROM restaurants r
          LEFT JOIN users u ON u.restaurant_id=r.id AND u.role='restaurant_admin'
          WHERE 1=1";
$params = []; $types = "";
if ($search) { $query .= " AND (r.name LIKE ? OR r.email LIKE ? OR r.address LIKE ?)"; $s = "%$search%"; $params = [$s,$s,$s]; $types = "sss"; }
if ($filter === 'active')   $query .= " AND r.status=1";
if ($filter === 'inactive') $query .= " AND r.status=0";
$query .= " ORDER BY r.created_at DESC";
$stmt = $conn->prepare($query);
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$restaurants = $stmt->get_result();
?>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.5rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">Restaurants</h1>
    <p style="color:var(--text-muted);font-size:.875rem">Manage all restaurant partners — each has its own Dabil wallet</p>
  </div>
  <button class="btn btn-primary btn-md" onclick="openModal('createModal')">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v8M8 12h8"/></svg>
    Add Restaurant
  </button>
</div>

<?php if ($success): ?><div class="alert alert-success"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><?php echo $success; ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-error"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg><?php echo htmlspecialchars($error); ?></div><?php endif; ?>

<div style="display:flex;align-items:center;gap:12px;margin-bottom:20px;flex-wrap:wrap">
  <form method="GET" style="display:flex;gap:8px;flex:1;min-width:220px">
    <div style="position:relative;flex:1;max-width:320px">
      <svg style="position:absolute;left:12px;top:50%;transform:translateY(-50%);width:15px;height:15px;stroke:var(--text-light);fill:none" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
      <input type="text" name="search" placeholder="Search restaurants…" value="<?php echo htmlspecialchars($search); ?>"
             style="width:100%;height:40px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 14px 0 36px;font-size:.85rem;font-family:var(--font);outline:none;transition:all .2s"
             onfocus="this.style.borderColor='var(--primary)'" onblur="this.style.borderColor='var(--border)'">
    </div>
    <input type="hidden" name="filter" value="<?php echo htmlspecialchars($filter); ?>">
    <button type="submit" class="btn btn-secondary btn-sm">Search</button>
  </form>
  <div style="display:flex;gap:6px">
    <?php foreach(['all'=>'All','active'=>'Active','inactive'=>'Inactive'] as $k=>$l): ?>
    <a href="?filter=<?php echo $k; ?><?php echo $search?"&search=".urlencode($search):''; ?>"
       class="btn btn-sm <?php echo $filter===$k?'btn-primary':'btn-secondary'; ?>"><?php echo $l; ?></a>
    <?php endforeach; ?>
  </div>
</div>

<div class="card">
  <?php if ($restaurants->num_rows === 0): ?>
    <div style="padding:60px;text-align:center;color:var(--text-muted)">
      <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block"><path d="M3 11l19-9-9 19-2-8-8-2z"/></svg>
      <p style="font-weight:700;margin-bottom:6px">No restaurants found</p>
      <button class="btn btn-primary btn-sm" onclick="openModal('createModal')" style="margin-top:12px">Add First Restaurant</button>
    </div>
  <?php else: ?>
  <div style="overflow-x:auto">
  <table class="data-table">
    <thead><tr><th>Restaurant</th><th>Admin</th><th>Menu Items</th><th>Orders</th><th>Dabil Wallet</th><th>Status</th><th>Created</th><th>Actions</th></tr></thead>
    <tbody>
    <?php while($r = $restaurants->fetch_assoc()): ?>
      <tr>
        <td>
          <div style="font-weight:700"><?php echo htmlspecialchars($r['name']); ?></div>
          <div style="font-size:.72rem;color:var(--text-muted)"><?php echo htmlspecialchars($r['email']); ?></div>
          <?php if($r['address']): ?><div style="font-size:.7rem;color:var(--text-light)"><?php echo htmlspecialchars($r['address']); ?></div><?php endif; ?>
        </td>
        <td>
          <div style="font-size:.82rem;font-weight:500"><?php echo htmlspecialchars($r['admin_name'] ?? '—'); ?></div>
          <div style="font-size:.7rem;color:var(--text-muted)"><?php echo htmlspecialchars($r['admin_email'] ?? ''); ?></div>
        </td>
        <td style="font-weight:600"><?php echo $r['menu_count']; ?></td>
        <td style="font-weight:600"><?php echo $r['order_count']; ?></td>
        <td>
          <div style="font-weight:700;color:var(--success)">₦<?php echo number_format($r['wallet_balance'], 2); ?></div>
          <div style="font-size:.68rem;color:var(--text-muted)">Dabil Wallet</div>
        </td>
        <td><span class="badge <?php echo $r['status']?'badge-success':'badge-error'; ?>"><?php echo $r['status']?'Active':'Inactive'; ?></span></td>
        <td style="font-size:.78rem;color:var(--text-muted)"><?php echo date('M j, Y', strtotime($r['created_at'])); ?></td>
        <td>
          <div style="display:flex;gap:6px;flex-wrap:wrap">
            <a href="?action=edit&id=<?php echo $r['id']; ?>" class="btn btn-secondary btn-sm">Edit</a>
            <a href="?action=toggle&id=<?php echo $r['id']; ?>"
               class="btn btn-sm <?php echo $r['status']?'btn-danger':'btn-success'; ?>"
               onclick="return confirm('<?php echo $r['status']?'Deactivate':'Activate'; ?> this restaurant?')">
              <?php echo $r['status']?'Deactivate':'Activate'; ?>
            </a>
            <form method="POST" style="display:inline"
                  onsubmit="return confirm('Permanently delete <?php echo addslashes($r['name']); ?>? This cannot be undone.')">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?php echo $r['id']; ?>">
              <button type="submit" class="btn btn-danger btn-sm">Delete</button>
            </form>
          </div>
        </td>
      </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>
</div>

<!-- Create Modal -->
<div class="modal-backdrop" id="createModal">
  <div class="modal">
    <div class="modal-header">
      <h3>Add New Restaurant</h3>
      <button class="modal-close" onclick="closeModal('createModal')"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="create">
      <div class="modal-body" style="max-height:65vh;overflow-y:auto">
        <p style="font-size:.78rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--primary);margin-bottom:16px">Restaurant Details</p>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
          <div class="form-group"><label>Restaurant Name *</label><input type="text" name="name" class="form-control" placeholder="e.g. Mambila Restaurant" required></div>
          <div class="form-group"><label>Email *</label><input type="email" name="email" class="form-control" placeholder="restaurant@email.com" required></div>
          <div class="form-group"><label>Phone</label><input type="tel" name="phone" class="form-control" placeholder="08012345678"></div>
          <div class="form-group"><label>Address</label><input type="text" name="address" class="form-control" placeholder="City / Area"></div>
        </div>
        <div class="form-group" style="margin-bottom:20px"><label>Description</label><textarea name="description" class="form-control" rows="2" placeholder="Brief description…"></textarea></div>
        <div style="background:var(--success-bg);border:1px solid #BBF7D0;border-radius:10px;padding:10px 14px;margin-bottom:16px;font-size:.78rem;color:var(--success);display:flex;align-items:center;gap:8px">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4"/><path d="M3 5v14a2 2 0 002 2h16v-5"/><path d="M18 12a2 2 0 000 4h4v-4z"/></svg>
          A Dabil wallet will be automatically created for this restaurant.
        </div>
        <p style="font-size:.78rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--primary);margin-bottom:16px;border-top:1px solid var(--border);padding-top:16px">Restaurant Admin Account</p>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
          <div class="form-group"><label>Admin Full Name</label><input type="text" name="admin_name" class="form-control" placeholder="John Doe"></div>
          <div class="form-group"><label>Admin Email</label><input type="email" name="admin_email" class="form-control" placeholder="admin@email.com"></div>
          <div class="form-group"><label>Admin Phone</label><input type="tel" name="admin_phone" class="form-control" placeholder="08012345678"></div>
          <div class="form-group"><label>Admin Password</label><input type="password" name="admin_password" class="form-control" placeholder="Min. 6 characters"></div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('createModal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-md">Create Restaurant</button>
      </div>
    </form>
  </div>
</div>

<!-- Edit Modal -->
<?php if ($edit_restaurant): ?>
<div class="modal-backdrop" id="editModal">
  <div class="modal">
    <div class="modal-header">
      <h3>Edit — <?php echo htmlspecialchars($edit_restaurant['name']); ?></h3>
      <a href="restaurants.php" class="modal-close"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></a>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="restaurant_id" value="<?php echo $edit_restaurant['id']; ?>">
      <div class="modal-body" style="max-height:65vh;overflow-y:auto">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
          <div class="form-group"><label>Restaurant Name *</label><input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($edit_restaurant['name']); ?>" required></div>
          <div class="form-group"><label>Email *</label><input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($edit_restaurant['email']); ?>" required></div>
          <div class="form-group"><label>Phone</label><input type="tel" name="phone" class="form-control" value="<?php echo htmlspecialchars($edit_restaurant['phone'] ?? ''); ?>"></div>
          <div class="form-group"><label>Address</label><input type="text" name="address" class="form-control" value="<?php echo htmlspecialchars($edit_restaurant['address'] ?? ''); ?>"></div>
        </div>
        <div class="form-group"><label>Description</label><textarea name="description" class="form-control" rows="2"><?php echo htmlspecialchars($edit_restaurant['description'] ?? ''); ?></textarea></div>
        <div class="form-group" style="margin-bottom:0;border-top:1px solid var(--border);padding-top:16px">
          <label>Reset Admin Password <span style="font-weight:400;text-transform:none;color:var(--text-light)">(leave blank to keep)</span></label>
          <input type="password" name="admin_password" class="form-control" placeholder="New password…">
        </div>
      </div>
      <div class="modal-footer">
        <a href="restaurants.php" class="btn btn-secondary btn-md">Cancel</a>
        <button type="submit" class="btn btn-primary btn-md">Save Changes</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>


<?php
// Auto-open correct modal via JS (avoids inline style conflict with closeModal)
$auto_open = '';
if ($action === 'create' && $error) $auto_open = 'createModal';
if (!empty($edit_restaurant))       $auto_open = 'editModal';
?>
<?php if ($auto_open): ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
    openModal('<?php echo $auto_open; ?>');
});
</script>
<?php endif; ?>

<?php include("includes/footer.php"); ?>
