<?php
// /api/towlens/shares.php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

session_start();

$ROOT = realpath(__DIR__ . '/..');
if (!$ROOT) { http_response_code(500); echo json_encode(['error' => 'Server path failed']); exit; }

$config = require $ROOT . '/lib/config.php';
require $ROOT . '/lib/db.php';
require $ROOT . '/lib/helpers.php';
require_once $ROOT . '/lib/mailer.php'; // if you have this

require_admin_auth($config);

if (!($pdo instanceof PDO)) { http_response_code(500); echo json_encode(['error' => 'DB unavailable']); exit; }
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$user = $_SESSION['user'] ?? [];
$role = $user['role'] ?? '';
if (!in_array($role, ['admin','org_admin'], true)) {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden']);
    exit;
}

function jresp($d, int $s=200){ http_response_code($s); echo json_encode($d,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

// Ensure share table exists (if not already)
$pdo->exec("
CREATE TABLE IF NOT EXISTS request_shares (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  request_id INT UNSIGNED NOT NULL,
  token CHAR(64) NOT NULL UNIQUE,
  send_channel ENUM('email','sms','whatsapp','manual') DEFAULT 'email',
  last_sent_at DATETIME DEFAULT NULL,
  open_count INT UNSIGNED NOT NULL DEFAULT 0,
  first_open_at DATETIME DEFAULT NULL,
  expires_at DATETIME DEFAULT NULL,
  sla_due_at DATETIME DEFAULT NULL,
  status ENUM('pending','sent','opened','completed','expired','cancelled') NOT NULL DEFAULT 'pending',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (request_id) REFERENCES requests(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

if ($method === 'GET') {
    $requestId = isset($_GET['request_id']) ? (int)$_GET['request_id'] : 0;
    if ($requestId <= 0) jresp(['error' => 'request_id required'], 400);

    $stmt = $pdo->prepare("
      SELECT id, request_id, token, send_channel, last_sent_at, open_count,
             first_open_at, expires_at, sla_due_at, status, created_at
      FROM request_shares
      WHERE request_id = ?
      ORDER BY id DESC
    ");
    $stmt->execute([$requestId]);
    jresp($stmt->fetchAll(PDO::FETCH_ASSOC));
}

if ($method === 'POST') {
    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true) ?? [];

    $requestId   = (int)($data['request_id'] ?? 0);
    $channel     = $data['send_channel'] ?? 'email';
    $expiresHours = (int)($data['expires_hours'] ?? 72);

    if ($requestId <= 0) jresp(['error' => 'request_id required'], 400);
    if (!in_array($channel, ['email','sms','whatsapp','manual'], true)) {
        jresp(['error' => 'Invalid send_channel'], 400);
    }

    // Confirm request exists
    $chk = $pdo->prepare("SELECT id, customer_email FROM requests WHERE id = ?");
    $chk->execute([$requestId]);
    $req = $chk->fetch(PDO::FETCH_ASSOC);
    if (!$req) jresp(['error' => 'Request not found'], 404);

    $token = bin2hex(random_bytes(32)); // 64-char
    $expiresAt = (new DateTimeImmutable())->modify("+{$expiresHours} hours")->format('Y-m-d H:i:s');

    $ins = $pdo->prepare("
      INSERT INTO request_shares
        (request_id, token, send_channel, expires_at, status, created_at)
      VALUES
        (?, ?, ?, ?, 'pending', NOW())
    ");
    $ins->execute([$requestId, $token, $channel, $expiresAt]);
    $shareId = (int)$pdo->lastInsertId();

    // Optional: send email/SMS here depending on channel
    // Example email stub (you can customise / wrap):
    if ($channel === 'email' && !empty($req['customer_email'])) {
        $base   = rtrim($config['base_url'] ?? '', '/');
        $link   = $base . '/towlens/view.php?token=' . urlencode($token);
        $to     = $req['customer_email'];
        $subj   = 'Please upload your vehicle photos';
        $body   = "Hi,\n\nPlease use the secure link below to upload your photos:\n{$link}\n\nThank you.";

        try {
            send_mail($to, $subj, nl2br(htmlentities($body)));
            $upd = $pdo->prepare("
              UPDATE request_shares
              SET status = 'sent', last_sent_at = NOW()
              WHERE id = ?
            ");
            $upd->execute([$shareId]);
        } catch (Throwable $e) {
            // leave as pending if mail fails
        }
    }

    // Log event
    $ev = $pdo->prepare("
      INSERT INTO towlens_events (request_id, share_id, event_type, details, created_by)
      VALUES (?, ?, 'LINK_CREATED', ?, ?)
    ");
    $ev->execute([
        $requestId,
        $shareId,
        json_encode(['channel' => $channel]),
        $user['email'] ?? 'system'
    ]);

    jresp(['id' => $shareId, 'token' => $token], 201);
}

header('Allow: GET, POST');
jresp(['error' => 'Method not allowed'], 405);
