<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/inc/auth.php';


require_once __DIR__ . '/inc/layout.php';
require_once __DIR__ . '/inc/activity_log.php';

if (empty($_SESSION['user_id'])) {
    header("Location: index.html?e=1");
    exit;
}

$pdo = function_exists('db') ? db() : ($GLOBALS['pdo'] ?? null);
if (!$pdo instanceof PDO) {
    http_response_code(500);
    die('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$branchId = (int)($_SESSION['branch_id'] ?? 1);
$userId   = (int)($_SESSION['user_id'] ?? 0);
$role     = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));

/* ===== تعريب حالات المهام ===== */
$TASK_STATUS = [
    'OPEN'   => 'مفتوحة',
    'DONE'   => 'قيد التنفيذ',
    'CLOSED' => 'مغلقة',
];

/* ===== تعريب الأولويات ===== */
$TASK_PRIORITY = [
    'HIGH'   => 'عالية',
    'MEDIUM' => 'متوسطة',
    'LOW'    => 'منخفضة',
];

/* ===== اسم الفرع ===== */
try {
    $st = $pdo->prepare("SELECT name_ar FROM branches WHERE id = ? LIMIT 1");
    $st->execute([$branchId]);
    $currentBranchName = (string)($st->fetchColumn() ?: 'أبوظبي');
} catch (Throwable $e) {
    $currentBranchName = match ($branchId) {
        2 => 'دبي',
        3 => 'الشارقة',
        4 => 'العين',
        default => 'أبوظبي',
    };
}

/* ===== رسائل بعد التحويل ===== */
$msg = trim((string)($_GET['msg'] ?? ''));
$err = trim((string)($_GET['err'] ?? ''));

/* ===== CSRF Token ===== */
if (empty($_SESSION['task_form_token'])) {
    $_SESSION['task_form_token'] = bin2hex(random_bytes(16));
}
$token = (string)$_SESSION['task_form_token'];

/* ===== قيم افتراضية ===== */
$formTitle    = '';
$formDue      = '';
$formStatus   = 'OPEN';
$formPriority = 'MEDIUM';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postedToken = (string)($_POST['token'] ?? '');

    if ($postedToken === '' || !hash_equals($token, $postedToken)) {
        header("Location: " . u('task_add.php?err=' . urlencode('تم منع إعادة الإرسال. حاول مرة أخرى.')));
        exit;
    }

    $_SESSION['task_form_token'] = bin2hex(random_bytes(16));

    $title    = trim((string)($_POST['title'] ?? ''));
    $due      = trim((string)($_POST['due_date'] ?? ''));
    $status   = strtoupper(trim((string)($_POST['status'] ?? 'OPEN')));
    $priority = strtoupper(trim((string)($_POST['priority'] ?? 'MEDIUM')));

    $formTitle    = $title;
    $formDue      = $due;
    $formStatus   = $status;
    $formPriority = $priority;

    if (!array_key_exists($status, $TASK_STATUS)) {
        $status = 'OPEN';
    }

    if (!array_key_exists($priority, $TASK_PRIORITY)) {
        $priority = 'MEDIUM';
    }

    $dueVal = ($due !== '') ? $due : null;

    if ($title === '') {
        header("Location: " . u('task_add.php?err=' . urlencode('اكتب ملخص المهمة')));
        exit;
    }

    $dupe = $pdo->prepare("
        SELECT id
        FROM tasks
        WHERE branch_id = ?
          AND title = ?
          AND created_at >= (NOW() - INTERVAL 10 SECOND)
        LIMIT 1
    ");
    $dupe->execute([$branchId, $title]);
    $exists = (int)($dupe->fetchColumn() ?: 0);

    if ($exists > 0) {
        header("Location: " . u('tasks.php?msg=' . urlencode('تمت إضافة المهمة بالفعل (تم منع التكرار).')));
        exit;
    }

    $ins = $pdo->prepare("
        INSERT INTO tasks (branch_id, title, status, priority, due_date, created_at, created_by)
        VALUES (?, ?, ?, ?, ?, NOW(), ?)
    ");
    $ins->execute([$branchId, $title, $status, $priority, $dueVal, ($userId ?: null)]);
$taskId = (int)$pdo->lastInsertId();

activity_log(
    $pdo,
    'task_created',
    'tasks',
    'task',
    $taskId,
    'تم إنشاء مهمة جديدة فقط بدون احتساب نقاط',
    'إضافة مهمة',
    '🧾',
    '#64748b'
);
    header("Location: " . u('tasks.php?msg=' . urlencode('تمت إضافة المهمة لفرع: ' . $currentBranchName)));
    exit;
}


render_layout_start('إضافة مهمة');
?>

<style>
  :root{
    --bg-card:rgba(255,255,255,.05);
    --line:rgba(255,255,255,.08);
    --text:#ffffff;
    --muted:rgba(255,255,255,.68);
    --gold:#d4af37;
    --shadow:0 18px 40px rgba(0,0,0,.16);
  }

  body{
    background:
      radial-gradient(circle at 20% 20%, rgba(10,77,87,.85), transparent 40%),
      radial-gradient(circle at 80% 80%, rgba(13,106,122,.55), transparent 40%),
      #021d23;
  }

  .task-add-page{
    color:var(--text);
    width:100%;
    max-width:1200px;
    margin:0 auto;
    padding:0 20px 24px;
  }

  .task-add-page *{
    box-sizing:border-box;
  }

  .task-add-page .topbar-local{
    min-height:68px;
    display:flex;
    align-items:center;
    justify-content:flex-start;
    direction:ltr;
    gap:14px;
    padding:10px 16px;
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    position:sticky;
    top:12px;
    z-index:10;
    margin:0 0 22px;
    backdrop-filter:blur(12px);
  }

  .task-add-page .btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:46px;
    padding:0 18px;
    border-radius:999px;
    border:1px solid rgba(212,175,55,.25);
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    font-weight:900;
    color:#1d1600;
    cursor:pointer;
    text-decoration:none;
    box-shadow:0 12px 24px rgba(212,175,55,.18);
    transition:.18s ease;
    white-space:nowrap;
    direction:rtl;
  }

  .task-add-page .btn:hover{
    transform:translateY(-2px);
    box-shadow:0 16px 28px rgba(212,175,55,.24);
  }

  .task-add-page .page-head{
    max-width:900px;
    margin:0 auto 16px;
    text-align:right;
  }

  .task-add-page .pageTitle{
    font-size:30px;
    font-weight:900;
    color:#ffffff;
    margin:0;
    line-height:1.1;
  }

  .task-add-page .pageSub{
    color:rgba(255,255,255,.72);
    font-size:15px;
    line-height:1.8;
    margin-top:8px;
  }

  .task-add-page .msg{
    max-width:900px;
    margin:12px auto;
    padding:12px 14px;
    border-radius:14px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
  }

  .task-add-page .ok{
    color:#86efac;
  }

  .task-add-page .err{
    color:#fca5a5;
  }

  .task-add-page .card{
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    padding:16px;
    max-width:900px;
    margin:0 auto;
    backdrop-filter:blur(12px);
  }

  .task-add-page label{
    display:block;
    margin:0 0 8px;
    font-weight:800;
    color:#ffffff;
  }

  .task-add-page input,
  .task-add-page select{
    width:100%;
    height:46px;
    border-radius:14px;
    border:1px solid var(--line);
    padding:0 14px;
    background:rgba(255,255,255,.05);
    font-family:inherit;
    outline:none;
    color:#fff;
  }

  .task-add-page input::placeholder{
    color:rgba(255,255,255,.45);
  }

  .task-add-page select option{
    background:#0b1f26;
    color:#fff;
  }

  .task-add-page input:focus,
  .task-add-page select:focus{
    border-color:rgba(212,175,55,.45);
    box-shadow:0 0 0 4px rgba(212,175,55,.12);
    background:rgba(255,255,255,.06);
  }

  .task-add-page .grid{
    display:grid;
    grid-template-columns:repeat(3, minmax(0, 1fr));
    gap:12px;
  }

  .task-add-page .span-3{
    grid-column:1 / -1;
  }

  .task-add-page .save{
    width:100%;
    height:48px;
    border:0;
    border-radius:14px;
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    color:#1d1600;
    font-weight:900;
    cursor:pointer;
    font-family:inherit;
    box-shadow:0 12px 28px rgba(212,175,55,.24);
    transition:.18s ease;
  }

  .task-add-page .save:hover{
    transform:translateY(-1px);
    box-shadow:0 16px 32px rgba(212,175,55,.30);
  }

  .task-add-page .note{
    max-width:900px;
    margin:16px auto 0;
    text-align:right;
    color:var(--muted);
    line-height:1.9;
    font-size:15px;
  }

  @media (max-width:980px){
    .task-add-page .grid{
      grid-template-columns:1fr;
    }

    .task-add-page .card,
    .task-add-page .page-head,
    .task-add-page .note,
    .task-add-page .msg{
      max-width:100%;
    }
  }

  @media (max-width:700px){
    .task-add-page{
      padding:0 14px 20px;
    }

    .task-add-page .pageTitle{
      font-size:24px;
    }

    .task-add-page .topbar-local{
      padding:10px 12px;
    }

    .task-add-page .btn{
      height:42px;
      padding:0 14px;
    }
  }
  /* زر الرجوع + زر الحفظ بتأثير ذهبي احترافي */
.task-add-page .btn,
.task-add-page .save{
  position:relative;
  overflow:hidden;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  height:48px;
  padding:0 22px;
  border-radius:999px;
  border:1px solid rgba(212,175,55,.55);
  background:linear-gradient(135deg,#ffd76a,#d4af37);
  color:#1a1400 !important;
  font-weight:900;
  font-size:14px;
  text-decoration:none;
  cursor:pointer;
  box-shadow:
    0 15px 32px rgba(212,175,55,.35),
    0 0 25px rgba(212,175,55,.25),
    inset 0 2px 6px rgba(255,255,255,.35);
  transition:all .25s ease;
}

/* زر الحفظ يكون عريض */
.task-add-page .save{
  width:100%;
  border-radius:16px;
  font-family:inherit;
}

/* اللمعة */
.task-add-page .btn::after,
.task-add-page .save::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:50%;
  height:100%;
  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,255,255,.62),
    transparent
  );
  transform:skewX(-20deg);
  animation:taskAddBtnShine 3.8s infinite;
  pointer-events:none;
}

@keyframes taskAddBtnShine{
  0%{ left:-70%; opacity:0; }
  40%{ opacity:.9; }
  100%{ left:130%; opacity:0; }
}

/* hover */
.task-add-page .btn:hover,
.task-add-page .save:hover{
  transform:translateY(-3px) scale(1.03);
  box-shadow:
    0 22px 42px rgba(212,175,55,.45),
    0 0 36px rgba(212,175,55,.35),
    inset 0 2px 6px rgba(255,255,255,.45);
}

/* ضغط */
.task-add-page .btn:active,
.task-add-page .save:active{
  transform:scale(.96);
}
</style>

<div class="task-add-page">
  <div class="topbar-local">
    <a class="btn" href="<?= h(u('tasks.php')) ?>">رجوع للمهام</a>
  </div>

  <div class="page-head">
    <h1 class="pageTitle">إضافة مهمة</h1>
    <div class="pageSub">سيتم حفظ المهمة داخل الفرع الحالي مباشرة</div>
  </div>

  <?php if ($msg !== ''): ?>
    <div class="msg ok"><?= h($msg) ?></div>
  <?php endif; ?>

  <?php if ($err !== ''): ?>
    <div class="msg err"><?= h($err) ?></div>
  <?php endif; ?>

  <div class="card">
    <form method="post" autocomplete="off">
      <input type="hidden" name="token" value="<?= h($token) ?>">

      <div class="grid">
        <div class="span-3">
          <label>ملخص المهمة</label>
          <input
            type="text"
            name="title"
            required
            placeholder="مثال: متابعة ملف..."
            value="<?= h($formTitle) ?>"
          >
        </div>

        <div>
          <label>الحالة</label>
          <select name="status">
            <?php foreach ($TASK_STATUS as $code => $label): ?>
              <option value="<?= h($code) ?>" <?= $formStatus === $code ? 'selected' : '' ?>>
                <?= h($label) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div>
          <label>الأولوية</label>
          <select name="priority">
            <?php foreach ($TASK_PRIORITY as $pCode => $pLabel): ?>
              <option value="<?= h($pCode) ?>" <?= $formPriority === $pCode ? 'selected' : '' ?>>
                <?= h($pLabel) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div>
          <label>تاريخ الاستحقاق</label>
          <input type="date" name="due_date" value="<?= h($formDue) ?>">
        </div>

        <div class="span-3">
          <button class="save" type="submit">حفظ المهمة</button>
        </div>
      </div>
    </form>
  </div>

  <div class="note">
    سيتم الحفظ تلقائيًا داخل فرع: <?= h($currentBranchName) ?>
  </div>
</div>

<?php render_layout_end(); ?>