<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('projects.manage');

require_once __DIR__ . '/../config/database.php';

requirePermission('manage_tasks');

$projectId = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 0;
$phaseId   = isset($_GET['phase_id']) ? (int)$_GET['phase_id'] : 0;

$message = '';

// If no project_id yet -> show Project selector screen (so Tasks menu works)
if ($projectId <= 0) {

    $projects = $pdo->query("
        SELECT id, project_name
        FROM projects
        ORDER BY created_at DESC
    ")->fetchAll(PDO::FETCH_ASSOC);

    require_once __DIR__ . '/../includes/header.php';
    require_once __DIR__ . '/../includes/sidebar.php';
    ?>
    <div class="main-content">

      <div class="page-header">
        <h2>Add Task</h2>
        <p class="page-subtitle">Step 1: Select a Project</p>
      </div>

      <form method="GET" class="card-form" style="max-width:620px;">
        <label>Select Project</label>
        <select name="project_id" required>
          <option value="">Choose project...</option>
          <?php foreach ($projects as $p): ?>
            <option value="<?= (int)$p['id'] ?>"><?= htmlspecialchars($p['project_name']) ?></option>
          <?php endforeach; ?>
        </select>

        <div style="margin-top:14px;display:flex;gap:10px;">
          <button type="submit" class="btn-primary">Next</button>
          <a class="btn-secondary" href="project_tasks.php">Cancel</a>
        </div>
      </form>

    </div>
    <?php
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}

// Fetch project
$pstmt = $pdo->prepare("SELECT * FROM projects WHERE id = ?");
$pstmt->execute([$projectId]);
$project = $pstmt->fetch(PDO::FETCH_ASSOC);
if (!$project) die("Project not found.");

// Fetch phases for project
$phasesStmt = $pdo->prepare("SELECT * FROM project_phases WHERE project_id = ? ORDER BY id ASC");
$phasesStmt->execute([$projectId]);
$phases = $phasesStmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch companies
$companies = $pdo->query("
    SELECT id, company_name
    FROM companies
    WHERE status = 'ACTIVE'
    ORDER BY company_name ASC
")->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $phaseId = (int)($_POST['phase_id'] ?? 0);
    $taskCode = trim($_POST['task_code'] ?? '');
    $taskType = $_POST['task_type'] ?? 'METER_INSTALL';
    $description = trim($_POST['description'] ?? '');
    $quantity = (int)($_POST['quantity'] ?? 0);
    $unitOfMeasure = trim($_POST['unit_of_measure'] ?? '');
    $assignedCompanyId = (int)($_POST['assigned_company_id'] ?? 0);
    $assignedUserId = (int)($_POST['assigned_user_id'] ?? 0);
    $priority = $_POST['priority'] ?? 'NORMAL';
    $status = $_POST['status'] ?? 'PENDING';
    $dueDate = $_POST['due_date'] ?? null;

    $unitCost  = (float)($_POST['unit_cost'] ?? 0);
    $unitPrice = (float)($_POST['unit_price'] ?? 0);

    if ($phaseId <= 0) $message = "Please select a phase.";
    elseif ($description === '') $message = "Please enter task description.";
    elseif ($quantity <= 0) $message = "Quantity must be 1 or more.";
    elseif ($assignedCompanyId <= 0) $message = "Please select an assigned company.";
    else {

        $insert = $pdo->prepare("
            INSERT INTO project_tasks (
                project_id, phase_id, task_code, task_type, description,
                quantity, unit_of_measure,
                assigned_company_id, assigned_user_id,
                status, priority, due_date,
                unit_cost, unit_price,
                created_by_user_id, created_at, updated_at
            ) VALUES (
                ?, ?, ?, ?, ?,
                ?, ?,
                ?, ?,
                ?, ?, ?,
                ?, ?,
                ?, NOW(), NOW()
            )
        ");

        $insert->execute([
            $projectId,
            $phaseId,
            $taskCode,
            $taskType,
            $description,
            $quantity,
            $unitOfMeasure,
            $assignedCompanyId,
            ($assignedUserId > 0 ? $assignedUserId : null),
            $status,
            $priority,
            ($dueDate ?: null),
            $unitCost,
            $unitPrice,
            (int)($_SESSION['user_id'] ?? 0)
        ]);

        header("Location: project_view.php?id=" . $projectId);
        exit;
    }
}

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<div class="main-content">

  <div class="page-header">
    <h2>Add Task</h2>
    <p class="page-subtitle">
      Project: <strong><?= htmlspecialchars($project['project_name'] ?? 'Project') ?></strong>
    </p>
  </div>

  <?php if ($message): ?>
    <div class="alert" style="background:#ffe7e7;border:1px solid #ffb3b3;padding:10px;border-radius:8px;margin-bottom:12px;">
      <?= htmlspecialchars($message) ?>
    </div>
  <?php endif; ?>

  <form method="POST" class="card-form" style="max-width:820px;">

    <label>Phase</label>
    <select name="phase_id" required>
      <option value="">Select Phase</option>
      <?php foreach ($phases as $ph): ?>
        <option value="<?= (int)$ph['id'] ?>" <?= ($phaseId==(int)$ph['id'])?'selected':'' ?>>
          <?= htmlspecialchars($ph['phase_name'] ?? 'Phase') ?>
        </option>
      <?php endforeach; ?>
    </select>

    <label>Task Code (optional)</label>
    <input type="text" name="task_code" placeholder="e.g. ELEC-DB-001" value="<?= htmlspecialchars($_POST['task_code'] ?? '') ?>">

    <label>Task Type</label>
    <select name="task_type">
      <option value="METER_INSTALL">Meter Install</option>
      <option value="METER_REPLACEMENT">Meter Replacement</option>
      <option value="ELECTRICAL_INSTALL">Electrical Install</option>
      <option value="DB_BOARD">DB Board / Distribution</option>
      <option value="CABLE_RUN">Cable Run</option>
      <option value="COC">CoC / Compliance</option>
      <option value="INSPECTION">Inspection</option>
      <option value="OTHER">Other</option>
    </select>

    <label>Description</label>
    <textarea name="description" rows="3" placeholder="Describe the work..." required><?= htmlspecialchars($_POST['description'] ?? '') ?></textarea>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
      <div>
        <label>Quantity</label>
        <input type="number" name="quantity" min="1" value="<?= htmlspecialchars($_POST['quantity'] ?? '1') ?>" required>
      </div>
      <div>
        <label>Unit of Measure</label>
        <input type="text" name="unit_of_measure" placeholder="e.g. meters, points, units" value="<?= htmlspecialchars($_POST['unit_of_measure'] ?? '') ?>">
      </div>
    </div>

    <label>Assign to Company</label>
    <select name="assigned_company_id" id="assigned_company_id" required>
      <option value="">Select Company</option>
      <?php foreach ($companies as $c): ?>
        <option value="<?= (int)$c['id'] ?>" <?= ((int)($_POST['assigned_company_id'] ?? 0) === (int)$c['id'])?'selected':'' ?>>
          <?= htmlspecialchars($c['company_name']) ?>
        </option>
      <?php endforeach; ?>
    </select>

    <label>Assign to User (optional)</label>
    <select name="assigned_user_id" id="assigned_user_id">
      <option value="">Select User (after company)</option>
    </select>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
      <div>
        <label>Status</label>
        <select name="status">
          <option value="PENDING">Pending</option>
          <option value="ASSIGNED">Assigned</option>
          <option value="IN_PROGRESS">In Progress</option>
          <option value="DONE">Done</option>
          <option value="BLOCKED">Blocked</option>
        </select>
      </div>
      <div>
        <label>Priority</label>
        <select name="priority">
          <option value="LOW">Low</option>
          <option value="NORMAL" selected>Normal</option>
          <option value="HIGH">High</option>
          <option value="URGENT">Urgent</option>
        </select>
      </div>
    </div>

    <label>Due Date (optional)</label>
    <input type="date" name="due_date" value="<?= htmlspecialchars($_POST['due_date'] ?? '') ?>">

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
      <div>
        <label>Unit Cost (optional)</label>
        <input type="number" step="0.01" name="unit_cost" value="<?= htmlspecialchars($_POST['unit_cost'] ?? '') ?>" placeholder="0.00">
      </div>
      <div>
        <label>Unit Price (optional)</label>
        <input type="number" step="0.01" name="unit_price" value="<?= htmlspecialchars($_POST['unit_price'] ?? '') ?>" placeholder="0.00">
      </div>
    </div>

    <div style="margin-top:14px;display:flex;gap:10px;">
      <button type="submit" class="btn-primary">Save Task</button>
      <a class="btn-secondary" href="project_view.php?id=<?= (int)$projectId ?>">Cancel</a>
    </div>

  </form>

</div>

<script>
(function(){
  const companySelect = document.getElementById('assigned_company_id');
  const userSelect = document.getElementById('assigned_user_id');

  async function loadUsers(companyId) {
    userSelect.innerHTML = '<option value="">Loading users...</option>';
    try {
      const res = await fetch('get_company_users.php?company_id=' + encodeURIComponent(companyId));
      const data = await res.json();

      let html = '<option value="">Select User (optional)</option>';
      data.forEach(u => {
        html += `<option value="${u.id}">${u.full_name}</option>`;
      });
      userSelect.innerHTML = html;
    } catch(e) {
      userSelect.innerHTML = '<option value="">Select User (optional)</option>';
    }
  }

  companySelect.addEventListener('change', function(){
    const id = this.value;
    if (!id) {
      userSelect.innerHTML = '<option value="">Select User (after company)</option>';
      return;
    }
    loadUsers(id);
  });

  const preSelectedCompany = companySelect.value;
  if (preSelectedCompany) {
    loadUsers(preSelectedCompany);
  }
})();
</script>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
