<?php
// admin/request_more.php

session_start();

$config = require __DIR__ . '/../lib/config.php';
require __DIR__ . '/../lib/db.php';
require __DIR__ . '/../lib/helpers.php';

require_admin_auth($config);

if ($pdo instanceof PDO) {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

// Current user / tenancy
$me        = $_SESSION['user'] ?? [];
$orgId     = isset($me['organisation_id']) ? (int)$me['organisation_id'] : 0;
$companyId = isset($me['company_id'])      ? (int)$me['company_id']      : 0;
$role      = $me['role'] ?? '';

$isAdmin    = ($role === 'admin');
$isOrgAdmin = ($role === 'org_admin') || !empty($me['is_org_admin']);

if ($orgId <= 0) {
    http_response_code(403);
    exit('Forbidden: no organisation scope.');
}

/**
 * Resolve request id robustly:
 * - Prefer POST/GET id or request_id.
 * - Fallback: parse ?id= from HTTP_REFERER.
 */
$id = 0;

$rawId =
    $_POST['id'] ??
    $_POST['request_id'] ??
    $_GET['id'] ??
    $_GET['request_id'] ??
    null;

if ($rawId !== null) {
    $id = (int)$rawId;
}

if ($id <= 0 && !empty($_SERVER['HTTP_REFERER'])) {
    $refQuery = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY);
    if ($refQuery) {
        parse_str($refQuery, $refParams);
        if (!empty($refParams['id'])) {
            $id = (int)$refParams['id'];
        } elseif (!empty($refParams['request_id'])) {
            $id = (int)$refParams['request_id'];
        }
    }
}

if ($id <= 0) {
    http_response_code(400);
    exit('Invalid request id');
}

$base = rtrim($config['base_url'] ?? '', '/');

// Tenancy-aware lookup: match view.php
if ($isOrgAdmin || $isAdmin) {
    $stmt = $pdo->prepare("
        SELECT *
        FROM requests
        WHERE id = ?
          AND organisation_id = ?
        LIMIT 1
    ");
    $stmt->execute([$id, $orgId]);
} else {
    if ($companyId <= 0) {
        http_response_code(403);
        exit('Forbidden: no company scope.');
    }
    $stmt = $pdo->prepare("
        SELECT *
        FROM requests
        WHERE id = ?
          AND organisation_id = ?
          AND company_id = ?
        LIMIT 1
    ");
    $stmt->execute([$id, $orgId, $companyId]);
}

$req = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$req) {
    http_response_code(404);
    exit('Request not found');
}

// Only allow when status is 'submitted'
$status = strtolower($req['status'] ?? '');
if ($status !== 'submitted') {
    $msg = urlencode('You can only request more photos when the request is in Submitted status.');
    header("Location: {$base}/admin/view.php?id={$id}&more_msg={$msg}");
    exit;
}

// Must have a customer email
if (empty($req['customer_email'])) {
    $msg = urlencode('No customer email on this request; unable to request more photos.');
    header("Location: {$base}/admin/view.php?id={$id}&more_msg={$msg}");
    exit;
}

// Reuse existing upload token
$token = $req['token'];
$uploadUrl = $base . '/public/upload.php?token=' . urlencode($token);

// Optionally extend expiry if missing or in the past
try {
    $extendDays = 7;
    $now = new DateTimeImmutable('now');
    $currentExpiry = $req['expires_at'] ? new DateTimeImmutable($req['expires_at']) : null;

    if (!$currentExpiry || $currentExpiry < $now) {
        $newExpiry = $now->modify('+' . $extendDays . ' days')->format('Y-m-d H:i:s');
        $upd = $pdo->prepare("UPDATE requests SET expires_at=? WHERE id=?");
        $upd->execute([$newExpiry, $id]);
    }
} catch (Throwable $e) {
    // non-fatal
}

/**
 * Work out branding + from address from company (if available)
 */
$brandName    = 'Towlens';
$fromEmail    = null;
$companyLabel = '';

try {
    $c = $pdo->prepare("
        SELECT name, brand_name, support_email
        FROM companies
        WHERE id = ?
          AND organisation_id = ?
        LIMIT 1
    ");
    $c->execute([(int)$req['company_id'], $orgId]);
    if ($co = $c->fetch(PDO::FETCH_ASSOC)) {
        if (!empty($co['brand_name'])) {
            $brandName = $co['brand_name'];
        } elseif (!empty($co['name'])) {
            $brandName = $co['name'];
        }
        if (!empty($co['support_email'])) {
            $fromEmail = $co['support_email'];
        }
        $companyLabel = $co['name'] ?: $brandName;
    }
} catch (Throwable $e) {
    // ignore; keep defaults
}

// Fallback From: from config or base_url domain
if (!$fromEmail) {
    if (!empty($config['mail']['from'])) {
        $fromEmail = $config['mail']['from'];
    } else {
        $host = parse_url($base, PHP_URL_HOST) ?: 'example.com';
        $fromEmail = 'no-reply@' . $host;
    }
}

$to   = $req['customer_email'];
$reg  = $req['reg_mark'] ?: '';
$name = $req['customer_name'] ?: '';
$exp  = $req['expires_at'] ?? null;

// Build nice plain-text email
$subject = $brandName . ' - Request for additional vehicle photos';

$lines = [];

$lines[] = ($name ? "Dear {$name}," : "Hello,");
$lines[] = "";
$lines[] = "Thank you for submitting photos" . ($reg ? " for vehicle {$reg}" : '') . ".";
$lines[] = "We now need a few additional images to complete our checks.";
$lines[] = "";
$lines[] = "Please use the secure upload link below to add more photos:";
$lines[] = $uploadUrl;
$lines[] = "";
if ($exp) {
    $lines[] = "This link is time-limited and may expire after: " . $exp;
    $lines[] = "";
}
$lines[] = "If you have any questions, please reply to this email.";
$lines[] = "";
$lines[] = "Best regards,";
$lines[] = $brandName . ($companyLabel && $companyLabel !== $brandName ? " ({$companyLabel})" : '');

$body = implode("\r\n", $lines);

// Headers
$headers  = 'From: ' . sprintf('"%s" <%s>', addslashes($brandName), $fromEmail) . "\r\n";
$headers .= "Reply-To: {$fromEmail}\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();

// Try to send
$sent = @mail($to, $subject, $body, $headers);

// (Optional) If you have a mail helper, replace above with it, e.g.:
// $sent = send_mail($to, $subject, $body, $fromEmail);

if ($sent) {
    $moreMsg = urlencode('Additional photo request email has been sent to ' . $to . '.');
} else {
    $moreMsg = urlencode(
        'Upload link refreshed, but automatic email sending failed. ' .
        'Please send this link manually to the customer: ' . $uploadUrl
    );
}

// Redirect back to view.php with outcome
header("Location: {$base}/admin/view.php?id={$id}&more_msg={$moreMsg}");
exit;
