<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/portal_auth.php';
auth_require_partner_portal();
$pdo = crm_pdo();
$page_title = 'Χρέωση Έργου';

$partnerId = auth_partner_id();
$projectId = (int)($_GET['project_id'] ?? $_POST['project_id'] ?? 0);
if ($partnerId <= 0 || $projectId <= 0) { http_response_code(403); exit('Missing partner or project.'); }

$allowed = false;
if (auth_is_admin_like()) {
    $allowed = true;
} else {
    $st = $pdo->prepare("SELECT COUNT(*) FROM project_assignments WHERE external_partner_id = :partner_id AND project_id = :project_id");
    $st->execute([':partner_id' => $partnerId, ':project_id' => $projectId]);
    $allowed = (int)$st->fetchColumn() > 0;
}
if (!$allowed) { http_response_code(403); exit('This project is not assigned to this partner.'); }

$st = $pdo->prepare("SELECT p.*, c.name AS customer_name FROM projects p LEFT JOIN customers c ON c.id = p.customer_id WHERE p.id = :id LIMIT 1");
$st->execute([':id' => $projectId]);
$project = $st->fetch();
if (!$project) die('Project not found.');

$quote = ['quote_amount' => '', 'notes' => '', 'status' => 'submitted'];
try {
    $st = $pdo->prepare("SELECT * FROM partner_project_costings WHERE project_id = :project_id AND external_partner_id = :partner_id LIMIT 1");
    $st->execute([':project_id' => $projectId, ':partner_id' => $partnerId]);
    $row = $st->fetch();
    if ($row) $quote = array_merge($quote, $row);
} catch (Throwable $e) {}

$ok=''; $errors=[];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $quoteAmount = (float)($_POST['quote_amount'] ?? 0);
    $notes = trim((string)($_POST['notes'] ?? ''));
    $status = trim((string)($_POST['status'] ?? 'submitted'));
    if ($quoteAmount < 0) $errors[] = 'Amount must be valid.';
    if (!in_array($status, ['draft','submitted','approved'], true)) $status = 'submitted';

    if (!$errors) {
        try {
            $st = $pdo->prepare("
                INSERT INTO partner_project_costings (project_id, external_partner_id, submitted_by_user_id, quote_amount, notes, status)
                VALUES (:project_id, :partner_id, :submitted_by_user_id, :quote_amount, :notes, :status)
                ON DUPLICATE KEY UPDATE
                    submitted_by_user_id = VALUES(submitted_by_user_id),
                    quote_amount = VALUES(quote_amount),
                    notes = VALUES(notes),
                    status = VALUES(status)
            ");
            $st->execute([
                ':project_id' => $projectId,
                ':partner_id' => $partnerId,
                ':submitted_by_user_id' => (int)(auth_user()['id'] ?? 0),
                ':quote_amount' => $quoteAmount,
                ':notes' => $notes !== '' ? $notes : null,
                ':status' => $status,
            ]);
            $ok = 'Partner costing saved.';
            $quote['quote_amount'] = $quoteAmount;
            $quote['notes'] = $notes;
            $quote['status'] = $status;
        } catch (Throwable $e) {
            $errors[] = 'Save failed: ' . $e->getMessage();
        }
    }
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Χρέωση Έργου</h1>
    <span><?php echo h(($project['code'] ?? '') . ' · ' . ($project['title'] ?? '') . ' · ' . ($project['customer_name'] ?? '')); ?></span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/gopools/public/partners/my_jobs.php<?php echo auth_is_admin_like() ? '?partner_id=' . (int)$partnerId : ''; ?>">Back to portal</a>
  </div>
</div>

<div class="grid-2">
  <div class="card">
    <?php if ($ok): ?><div class="alert-success"><?php echo h($ok); ?></div><?php endif; ?>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>
    <form method="post">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
      <?php if (auth_is_admin_like()): ?><input type="hidden" name="partner_id" value="<?php echo (int)$partnerId; ?>"><?php endif; ?>
      <div class="form-grid">
        <div class="form-group"><label>Ποσό χρέωσης</label><input type="number" step="0.01" min="0" name="quote_amount" value="<?php echo h((string)($quote['quote_amount'] ?? '')); ?>"></div>
        <div class="form-group"><label>Status</label><select name="status"><option value="draft" <?php echo (($quote['status'] ?? '') === 'draft') ? 'selected' : ''; ?>>draft</option><option value="submitted" <?php echo (($quote['status'] ?? 'submitted') === 'submitted') ? 'selected' : ''; ?>>submitted</option><?php if (auth_is_admin_like()): ?><option value="approved" <?php echo (($quote['status'] ?? '') === 'approved') ? 'selected' : ''; ?>>approved</option><?php endif; ?></select></div>
        <div class="form-group" style="grid-column:1/-1"><label>Notes</label><textarea name="notes"><?php echo h((string)($quote['notes'] ?? '')); ?></textarea></div>
      </div>
      <div class="form-actions"><button class="btn btn-primary" type="submit">Αποθήκευση χρέωσης</button></div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Τρέχουσα χρέωση</h1><span>Stored against this partner and project</span></div>
    <p><strong>Ποσό:</strong> € <?php echo h(number_format((float)($quote['quote_amount'] ?? 0), 2)); ?></p>
    <p><strong>Status:</strong> <?php echo h($quote['status'] ?? 'submitted'); ?></p>
    <p><strong>Notes:</strong> <?php echo h((string)($quote['notes'] ?? '')); ?></p>
  </div>
</div>

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

