<?php
require_once __DIR__ . '/../core/auth.php';
require_login();
$pdo = db();

$success = $error = "";

// ✅ فتح يومية جديدة
if (isset($_POST['open_shift'])) {
    $branch = $_POST['BranchID'];
    $emp    = $_SESSION['admin_id']; // الموظف الحالي

    // تأكد مفيش يومية مفتوحة لنفس الفرع
    $check = $pdo->prepare("SELECT * FROM DailyShifts WHERE BranchID=? AND CloseTime IS NULL");
    $check->execute([$branch]);
    if ($check->fetch()) {
        $error = "⚠️ يوجد يومية مفتوحة لهذا الفرع بالفعل!";
    } else {
        $stmt = $pdo->prepare("INSERT INTO DailyShifts (BranchID, ShiftDate, OpenTime, OpenedBy, OpeningBalance) 
                               VALUES (?,?,NOW(),?,?)");
        $stmt->execute([$branch, date("Y-m-d"), $emp, $_POST['OpeningBalance'] ?? 0]);
        $success = "✅ تم فتح اليومية بنجاح";
    }
}

// ✅ إغلاق يومية
if (isset($_POST['close_shift'])) {
    $shiftID = $_POST['ShiftID'];
    $emp     = $_SESSION['admin_id']; // الموظف الحالي
    $closingBalance = $_POST['ClosingBalance'] ?? 0;

    $stmt = $pdo->prepare("UPDATE DailyShifts 
                           SET CloseTime=NOW(), ClosedBy=?, ClosingBalance=? 
                           WHERE ShiftID=? AND CloseTime IS NULL");
    $stmt->execute([$emp, $closingBalance, $shiftID]);
    $success = "✅ تم إغلاق اليومية بنجاح";
}

// ✅ جلب الفروع
$branches = $pdo->query("SELECT BranchID, BranchName FROM Branches WHERE IsActive=1")->fetchAll();

// ✅ جلب اليوميات
$shifts = $pdo->query("SELECT d.*, b.BranchName, e.EmpName as OpenEmp, ee.EmpName as CloseEmp
                       FROM DailyShifts d
                       JOIN Branches b ON d.BranchID=b.BranchID
                       JOIN Employees e ON d.OpenedBy=e.EmpID
                       LEFT JOIN Employees ee ON d.ClosedBy=ee.EmpID
                       ORDER BY d.ShiftID DESC")->fetchAll();
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <title>إدارة اليوميات</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
       body {
      font-family: "Tajawal", Tahoma, Arial, sans-serif;
      background: #f5f7fa;
      margin: 0;
      padding: 0;
    }
    header {
      background: linear-gradient(135deg,#0f2027,#203a43,#2c5364);
      color: #fff;
      padding: 15px 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-shadow: 0 5px 20px rgba(0,0,0,0.3);
      position: relative;
    }
    header h1 {
      margin: 0;
      font-size: 24px;
      font-weight: bold;
      text-align: center;
      flex: 1;
    }

    /* بيانات المستخدم */
    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;
      background: rgba(255,255,255,0.1);
      padding: 6px 14px;
      border-radius: 50px;
      transition: all 0.3s ease-in-out;
    }
    .user-info:hover {
      background: rgba(255,255,255,0.2);
    }
    .user-info img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      object-fit: cover;
      border: 2px solid #1abc9c;
    }
    .user-info span {
      font-weight: bold;
      font-size: 14px;
    }
    .user-info a {
      background: #e74c3c;
      border: none;
      color: #fff;
      padding: 5px 12px;
      border-radius: 30px;
      font-size: 13px;
      text-decoration: none;
      transition: background 0.3s;
    }
    .user-info a:hover {
      background: #c0392b;
    }

    /* زر الوضع الليلي */
    #darkSwitch {
      background: #1abc9c;
      color: #fff;
      border: none;
      border-radius: 30px;
      padding: 8px 16px;
      cursor: pointer;
      font-weight: bold;
      transition: all 0.3s;
    }
    #darkSwitch:hover {
      background: #16a085;
    }

    /* الوضع الليلي */
    body.dark {
      background:#121212;
      color:#eee;
    }
    body.dark header {
      background: linear-gradient(135deg,#000,#333);
      border-bottom: 3px solid #1abc9c;
    }
    body.dark .user-info {
      background: rgba(255,255,255,0.1);
    }

    header h1 {
      margin: 0;
      font-size: 22px;
    }

    .container {
      display: flex;
      min-height: calc(100vh - 60px);
    }
    .card { border-radius:12px; box-shadow:0 4px 12px rgba(0,0,0,.1); }
    .card-header { background:linear-gradient(135deg,#0f2027,#203a43,#2c5364); color:#fff; }
  </style>
</head>
<body>
<header>
    <!-- بيانات المستخدم يمين -->
    <div class="user-info">
    <img src="uploads/<?= htmlspecialchars($_SESSION['avatar'] ?? 'default.png') ?>" 
            alt="Avatar" 
            class="rounded-circle border border-2 border-light"
            style="width:40px;height:40px;object-fit:cover;">
      <span><?= htmlspecialchars($_SESSION['admin_username']) ?></span>
      <a href="logout.php"><i class="fa-solid fa-right-from-bracket"></i> خروج</a>
    </div>

    <!-- عنوان الصفحة في الوسط -->
    <h1><i class="fa-solid fa-gauge-high"></i> لوحة التحكم</h1>

    <!-- زر الوضع الليلي شمال -->
    <button id="darkSwitch">🌙</button>
  </header>
  
  <div class="text-end mb-3">
  <a href="dashboard.php" class="btn btn-secondary">
    <i class="fa-solid fa-house"></i> الرئيسية
  </a>
</div>
<div class="container py-4">



  <div class="card mb-4">
    <div class="card-header">⚡ فتح يومية جديدة</div>
    <div class="card-body">
      <?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>
      <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>

      <form method="post" class="row g-3">
        <div class="col-md-4">
          <label class="form-label">الفرع</label>
          <select name="BranchID" class="form-select" required>
            <option value="">اختر الفرع</option>
            <?php foreach($branches as $b): ?>
              <option value="<?= $b['BranchID'] ?>"><?= htmlspecialchars($b['BranchName']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label">رصيد الافتتاح</label>
          <input type="number" step="0.01" name="OpeningBalance" class="form-control" value="0">
        </div>
        <div class="col-md-4 d-flex align-items-end">
          <button type="submit" name="open_shift" class="btn btn-success w-100">🚀 فتح اليومية</button>
        </div>
      </form>
    </div>
  </div>

  <div class="card">
    <div class="card-header">📋 قائمة اليوميات</div>
    <div class="card-body">
      <table class="table table-bordered text-center align-middle">
        <thead class="table-dark">
          <tr>
            <th>#</th>
            <th>الفرع</th>
            <th>تاريخ</th>
            <th>وقت الفتح</th>
            <th>فتح بواسطة</th>
            <th>رصيد البداية</th>
            <th>وقت الإغلاق</th>
            <th>قفل بواسطة</th>
            <th>رصيد النهاية</th>
            <th>الحالة</th>
            <th>إجراء</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($shifts as $s): ?>
            <tr>
              <td><?= $s['ShiftID'] ?></td>
              <td><?= htmlspecialchars($s['BranchName']) ?></td>
              <td><?= $s['ShiftDate'] ?></td>
              <td><?= $s['OpenTime'] ?></td>
              <td><?= htmlspecialchars($s['OpenEmp']) ?></td>
              <td><?= $s['OpeningBalance'] ?></td>
              <td><?= $s['CloseTime'] ?? '—' ?></td>
              <td><?= $s['CloseEmp'] ?? '—' ?></td>
              <td><?= $s['ClosingBalance'] ?></td>
              <td>
                <?php if ($s['CloseTime']): ?>
                  <span class="badge bg-danger">مغلقة</span>
                <?php else: ?>
                  <span class="badge bg-success">مفتوحة</span>
                <?php endif; ?>
              </td>
              <td>
                <?php if (!$s['CloseTime']): ?>
                  <form method="post" style="display:inline-block;">
                    <input type="hidden" name="ShiftID" value="<?= $s['ShiftID'] ?>">
                    <input type="number" step="0.01" name="ClosingBalance" placeholder="رصيد الإغلاق" class="form-control mb-1" required>
                    <button type="submit" name="close_shift" class="btn btn-sm btn-danger">🔒 إغلاق</button>
                  </form>
                <?php else: ?>
                  <span class="text-muted">—</span>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>
</body>
</html>
