<?php
/**
 * AJAX: Send or Resend an LPO Email for a specific requisition
 * File: ajax/send_lpo_email.php
 * Method: POST
 * Params: requisition_id (int), supplier_email (string, optional override)
 *
 * Response JSON:
 *   { success: bool, message: string }
 */

session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once '../layouts/dbconn.php';
require_once '../vendor/autoload.php';
require_once '../generate_lpo_pdf.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as MailException;

$req_id = isset($_POST['requisition_id']) ? (int)$_POST['requisition_id'] : 0;
$override_email = trim($_POST['supplier_email'] ?? '');

if (!$req_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid requisition ID.']);
    exit;
}

// Load requisition
$req_sql = "
    SELECT pr.*, u.full_name AS req_by_name
    FROM pharmacy_requisitions pr
    LEFT JOIN users u ON pr.requested_by = u.user_id
    WHERE pr.requisition_id = ?
";
$stmt = $conn->prepare($req_sql);
$stmt->bind_param("i", $req_id);
$stmt->execute();
$req = $stmt->get_result()->fetch_assoc();

if (!$req) {
    echo json_encode(['success' => false, 'message' => 'Requisition not found.']);
    exit;
}

// Load items
$items_stmt = $conn->prepare("
    SELECT item_name, quantity_requested AS reorder_quantity, unit_cost, notes
    FROM pharmacy_requisition_items WHERE requisition_id = ? ORDER BY item_id
");
$items_stmt->bind_param("i", $req_id);
$items_stmt->execute();
$items_res = $items_stmt->get_result();
$items = [];
$total = 0;
while ($row = $items_res->fetch_assoc()) {
    $items[] = $row;
    $total  += $row['reorder_quantity'] * $row['unit_cost'];
}

if (empty($items)) {
    echo json_encode(['success' => false, 'message' => 'No items found on this requisition.']);
    exit;
}

// Load supplier
$supplier_data = null;
if (!empty($req['notes'])) {
    // Try to extract supplier from first item's supplier FK via inventory
    $sup_stmt = $conn->prepare("
        SELECT ps.*, pi.preferred_supplier_id
        FROM pharmacy_inventory pi
        JOIN pharmacy_suppliers ps ON pi.preferred_supplier_id = ps.supplier_id
        WHERE pi.item_name = ? LIMIT 1
    ");
    $first_item = $items[0]['item_name'];
    $sup_stmt->bind_param("s", $first_item);
    $sup_stmt->execute();
    $supplier_data = $sup_stmt->get_result()->fetch_assoc();
}

// Resolve target email
$to_email = $override_email ?: ($supplier_data['email'] ?? '');
if (!$to_email || !filter_var($to_email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'No valid supplier email available. Please provide one.']);
    exit;
}

// System settings
$get_setting = function(string $k, string $d = '') use ($conn): string {
    $s = $conn->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ? LIMIT 1");
    $s->bind_param("s", $k);
    $s->execute();
    $r = $s->get_result()->fetch_assoc();
    return $r ? ($r['setting_value'] ?? $d) : $d;
};
$hosp_name    = $get_setting('hospital_name', 'ENT Hospital');
$hosp_email   = $get_setting('hospital_email', '');
$hosp_address = $get_setting('hospital_address', '');
$hosp_phone   = $get_setting('hospital_phone', '');
$hosp_logo    = $get_setting('hospital_logo', '');

// Map supplier data for PDF
$sup_arr = $supplier_data ? [
    'supplier_name'    => $supplier_data['supplier_name'] ?? '',
    'supplier_contact' => $supplier_data['contact_person'] ?? '',
    'supplier_phone'   => $supplier_data['phone'] ?? '',
    'supplier_address' => $supplier_data['address'] ?? '',
] : null;

// Add unit_of_measure to items (PDF needs it)
foreach ($items as &$it) {
    $inv = $conn->prepare("SELECT unit_of_measure FROM pharmacy_inventory WHERE item_name = ? LIMIT 1");
    $inv->bind_param("s", $it['item_name']);
    $inv->execute();
    $inv_row   = $inv->get_result()->fetch_assoc();
    $it['unit_of_measure'] = $inv_row['unit_of_measure'] ?? 'Units';
}
unset($it);

if (!defined('AREQ_LPO_DIR')) {
    define('AREQ_LPO_DIR', dirname(__DIR__) . '/lpo_pdfs/');
    if (!is_dir(AREQ_LPO_DIR)) { mkdir(AREQ_LPO_DIR, 0755, true); }
}

// Generate PDF
$pdf_path = generate_lpo_pdf_file(
    $req_id, $req['requisition_number'], $items, $total,
    $sup_arr, $hosp_name, $hosp_address, $hosp_phone, $hosp_email, $hosp_logo
);

if (!$pdf_path) {
    echo json_encode(['success' => false, 'message' => 'PDF generation failed.']);
    exit;
}

// Send email
$lpo_num = 'LPO-' . preg_replace('/^REQ-(?:AUTO-)?/', '', $req['requisition_number']);
try {
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Host       = $get_setting('smtp_host', 'smtp.gmail.com');
    $mail->SMTPAuth   = true;
    $mail->Username   = $get_setting('smtp_username', $hosp_email);
    $mail->Password   = $get_setting('smtp_password', '');
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = (int)$get_setting('smtp_port', '587');

    $mail->setFrom($hosp_email ?: $mail->Username, $hosp_name);
    $mail->addAddress($to_email, $supplier_data['supplier_name'] ?? 'Supplier');
    $mail->Subject = "Local Purchase Order {$lpo_num} — {$hosp_name}";
    $mail->isHTML(true);
    $mail->Body    = "<p>Dear Supplier,</p><p>Please find attached the LPO <strong>{$lpo_num}</strong> from {$hosp_name}.</p>"
                   . "<p>For queries contact: {$hosp_phone}</p>";
    $mail->addAttachment($pdf_path, basename($pdf_path));
    $mail->send();

    // Log the manual send
    $user_id   = (int)$_SESSION['user_id'];
    $sup_id    = $supplier_data['preferred_supplier_id'] ?? null;
    $fn        = basename($pdf_path);
    $tc        = count($items);
    $subj      = $mail->Subject;
    $log_stmt  = $conn->prepare("
        INSERT INTO auto_requisition_email_log
            (requisition_id, supplier_id, supplier_email, email_subject, triggered_by,
             sent_by, status, lpo_filename, items_count, total_amount)
        VALUES (?, ?, ?, ?, 'manual', ?, 'sent', ?, ?, ?)
    ");
    $log_stmt->bind_param("iissisd", $req_id, $sup_id, $to_email, $subj,
                                     $user_id, $fn, $tc, $total);
    $log_stmt->execute();

    echo json_encode(['success' => true, 'message' => "LPO emailed successfully to {$to_email}."]);

} catch (MailException $e) {
    // Log failed attempt
    $fn    = basename($pdf_path);
    $tc    = count($items);
    $err   = $e->getMessage();
    $uid   = (int)$_SESSION['user_id'];
    $f     = $conn->prepare("
        INSERT INTO auto_requisition_email_log
            (requisition_id, supplier_email, triggered_by, sent_by, status, error_message, lpo_filename, items_count, total_amount)
        VALUES (?, ?, 'manual', ?, 'failed', ?, ?, ?, ?)
    ");
    $f->bind_param("isissiid", $req_id, $to_email, $uid, $err, $fn, $tc, $total);
    $f->execute();

    echo json_encode(['success' => false, 'message' => 'Email failed: ' . $e->getMessage()]);
}