<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('repair_parts_manage');

$pdo = getDB();
$user = currentUser();

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['job_id'], $_POST['product_id'])) {
    $_SESSION['error'] = 'Invalid request.'; header('Location: repair_jobs.php'); exit;
}

$job_id = (int)$_POST['job_id'];
$product_id = (int)$_POST['product_id'];
$qty = max(1, (int)($_POST['quantity'] ?? 1));
$selling_price = (float)($_POST['selling_price'] ?? 0);

// Verify the job exists and is not delivered/cancelled
$stmt = $pdo->prepare("SELECT id, job_no, repair_status FROM repair_jobs WHERE id = ?");
$stmt->execute([$job_id]);
$job = $stmt->fetch();
if (!$job) { $_SESSION['error'] = 'Job not found.'; header('Location: repair_jobs.php'); exit; }
if (in_array($job['repair_status'], ['Delivered', 'Cancelled', 'Cannot Repair'])) {
    $_SESSION['error'] = 'Cannot add parts to a ' . $job['repair_status'] . ' job.';
    header("Location: view_repair_job.php?id=$job_id"); exit;
}

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare("SELECT id, product_name, current_stock, cost_price FROM products WHERE id = ? AND product_type = 'spare_part' AND status = 1 FOR UPDATE");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch();
    if (!$product) { throw new Exception('Invalid or inactive spare part.'); }
    if ($product['current_stock'] < $qty) {
        throw new Exception("Insufficient stock for '{$product['product_name']}'. Available: {$product['current_stock']}, requested: $qty");
    }

    $cost_price = $product['cost_price'];
    $total_price = $qty * $selling_price;

    $stmt = $pdo->prepare("INSERT INTO repair_job_parts (repair_job_id, product_id, quantity, cost_price, selling_price, total_price) VALUES (?,?,?,?,?,?)");
    $stmt->execute([$job_id, $product_id, $qty, $cost_price, $selling_price, $total_price]);

    $pdo->prepare("UPDATE products SET current_stock = current_stock - ? WHERE id = ?")->execute([$qty, $product_id]);

    // Get new balance after stock reduction
    $stmt = $pdo->prepare("SELECT current_stock FROM products WHERE id = ?");
    $stmt->execute([$product_id]);
    $new_balance = (int)$stmt->fetchColumn();

    $note = 'Used in repair job ' . $job['job_no'];
    $stmt = $pdo->prepare("INSERT INTO stock_movements (product_id, movement_type, reference_type, reference_id, quantity_in, quantity_out, balance_after, note, created_by) VALUES (?, 'repair_usage', 'repair_job', ?, 0, ?, ?, ?, ?)");
    $stmt->execute([$product_id, $job_id, $qty, $new_balance, $note, $user['id']]);

    // Update total_amount = parts_total + labour_charge - discount_amount
    $pdo->prepare("UPDATE repair_jobs SET parts_total = parts_total + ?, final_amount = parts_total + labour_charge - discount_amount, updated_at = NOW() WHERE id = ?")->execute([$total_price, $job_id]);

    $pdo->commit();
    $_SESSION['success'] = "Spare part '{$product['product_name']}' added successfully.";

} catch (Exception $e) {
    $pdo->rollBack();
    $_SESSION['error'] = 'Error: ' . $e->getMessage();
}

header("Location: view_repair_job.php?id=$job_id");
exit;
