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

$pdo = getDB();
$edit_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$job = null;

if ($edit_id) {
    $stmt = $pdo->prepare("SELECT * FROM repair_jobs WHERE id=?");
    $stmt->execute([$edit_id]);
    $job = $stmt->fetch();
    if (!$job) { header('Location: repair_jobs.php'); exit; }
}

$customers = $pdo->query("SELECT * FROM customers WHERE status=1 ORDER BY name")->fetchAll();
$technicians = $pdo->query("SELECT u.id, u.name FROM users u WHERE u.role_id = 4 AND u.status = 1 ORDER BY u.name")->fetchAll();
$spare_parts = $pdo->query("SELECT * FROM products WHERE product_type='Spare Part' AND status=1 AND current_stock > 0 ORDER BY product_name")->fetchAll();

// Get used parts if editing
$used_parts = [];
if ($edit_id) {
    $stmt = $pdo->prepare("SELECT rjp.*, p.product_name as product_name FROM repair_job_parts rjp JOIN products p ON rjp.product_id = p.id WHERE rjp.repair_job_id = ?");
    $stmt->execute([$edit_id]);
    $used_parts = $stmt->fetchAll();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'save_job') {
        $customer_id = (int)$_POST['customer_id'];
        $device_brand = trim($_POST['device_brand']);
        $device_model = trim($_POST['device_model']);
        $imei_number = trim($_POST['imei_number']);
        $device_color = trim($_POST['device_color']);
        $problem = trim($_POST['problem_description']);
        $condition_notes = trim($_POST['condition_notes']);
        $password_note = trim($_POST['password_note']);
        $accessories = trim($_POST['accessories_received']);
        $estimated_cost = (float)$_POST['estimated_cost'];
        $advance_payment = (float)$_POST['advance_payment'];
        $expected_date = $_POST['expected_delivery_date'] ?: null;
        $technician = !empty($_POST['assigned_technician']) ? (int)$_POST['assigned_technician'] : null;
        $priority = $_POST['priority'];
        $status = $_POST['status'];
        $internal_notes = trim($_POST['internal_notes']);
        $customer_notes = trim($_POST['customer_notes']);

        $parts_id = $_POST['parts_id'] ?? [];
        $parts_qty = $_POST['parts_qty'] ?? [];
        $parts_price = $_POST['parts_price'] ?? [];

        if (empty($customer_id) || empty($problem)) {
            $_SESSION['error'] = 'Customer and problem description are required.';
        } else {
            try {
                $pdo->beginTransaction();

                $parts_cost = 0;
                if ($edit_id) {
                    // Remove old parts
                    $pdo->prepare("DELETE FROM repair_job_parts WHERE repair_job_id=?")->execute([$edit_id]);
                    // Restore old stock
                    foreach ($used_parts as $op) {
                        $pdo->prepare("UPDATE products SET current_stock = current_stock + ? WHERE id = ?")->execute([$op['quantity'], $op['product_id']]);
                    }
                }

                // Process parts
                $parts_total = 0;
                if (!empty($parts_id)) {
                    foreach ($parts_id as $idx => $pid) {
                        if (empty($pid)) continue;
                        $qty = (int)($parts_qty[$idx] ?? 1);
                        $sprice = (float)($parts_price[$idx] ?? 0);
                        $total = $qty * $sprice;
                        $parts_total += $total;

                        // Check stock
                        $stock_check = $pdo->prepare("SELECT current_stock, cost_price FROM products WHERE id=?");
                        $stock_check->execute([(int)$pid]);
                        $prod = $stock_check->fetch();
                        if (!$prod || $prod['current_stock'] < $qty) {
                            throw new Exception("Insufficient stock for part ID $pid");
                        }

                        $cost_price = $prod['cost_price'];
                        // Insert part usage
                        $stmt = $pdo->prepare("INSERT INTO repair_job_parts (repair_job_id, product_id, quantity, cost_price, selling_price, total_price) VALUES (?,?,?,?,?,?)");
                        $stmt->execute([$edit_id ?: 0, (int)$pid, $qty, $cost_price, $sprice, $total]);
                        // Reduce stock
                        $pdo->prepare("UPDATE products SET current_stock = current_stock - ? WHERE id = ?")->execute([$qty, (int)$pid]);
                        // Stock movement
                        $pdo->prepare("INSERT INTO stock_movements (product_id, movement_type, quantity_out, reference_type, reference_id, notes, created_by) VALUES (?, 'Repair Use', ?, 'repair', ?, ?, ?)")
                            ->execute([(int)$pid, $qty, $edit_id ?: 'new', 'Used in repair job', $_SESSION['user_id']]);
                    }
                }

                $labour_charge = (float)$_POST['labour_charge'] ?? 0;
                $total_cost = $parts_total + $labour_charge;
                $paid_amount = $advance_payment;
                $due_amount = $total_cost - $paid_amount;

                if ($edit_id) {
                    $stmt = $pdo->prepare("UPDATE repair_jobs SET customer_id=?, device_brand=?, device_model=?, device_imei=?, device_color=?, problem_description=?, device_condition=?, device_password_note=?, accessories_received=?, estimated_cost=?, advance_payment=?, labour_charge=?, parts_total=?, final_amount=?, paid_amount=?, due_amount=?, expected_delivery_date=?, assigned_technician_id=?, priority=?, repair_status=?, internal_notes=?, customer_notes=? WHERE id=?");
                    $stmt->execute([$customer_id, $device_brand, $device_model, $imei_number, $device_color, $problem, $condition_notes, $password_note, $accessories, $estimated_cost, $advance_payment, $labour_charge, $parts_total, $total_cost, $paid_amount, $due_amount, $expected_date, $technician, $priority, $status, $internal_notes, $customer_notes, $edit_id]);

                    // Update parts for existing job
                    foreach ($used_parts as $op) {
                        if (in_array($op['id'], $parts_id)) continue; // skip if still used
                    }

                    // Log status change
                    $pdo->prepare("INSERT INTO repair_job_status_history (repair_job_id, new_status, changed_by) VALUES (?,?,?)")->execute([$edit_id, $status, $_SESSION['user_id']]);

                    logActivity('Updated Repair Job', 'Repairs', $edit_id);
                    $_SESSION['success'] = 'Repair job updated successfully.';
                } else {
                    $job_no = generateJobNo();
                    $stmt = $pdo->prepare("INSERT INTO repair_jobs (job_no, customer_id, device_brand, device_model, device_imei, device_color, problem_description, device_condition, device_password_note, accessories_received, estimated_cost, advance_payment, labour_charge, parts_total, final_amount, paid_amount, due_amount, expected_delivery_date, assigned_technician_id, priority, repair_status, internal_notes, customer_notes, created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                    $stmt->execute([$job_no, $customer_id, $device_brand, $device_model, $imei_number, $device_color, $problem, $condition_notes, $password_note, $accessories, $estimated_cost, $advance_payment, $labour_charge, $parts_total, $total_cost, $paid_amount, $due_amount, $expected_date, $technician, $priority, 'Received', $internal_notes, $customer_notes, $_SESSION['user_id']]);
                    $new_id = $pdo->lastInsertId();

                    // Update parts reference
                    $update_parts = $pdo->prepare("UPDATE repair_job_parts SET repair_job_id = ? WHERE repair_job_id = 0");
                    $update_parts->execute([$new_id]);

                    // Initial status history
                    $pdo->prepare("INSERT INTO repair_job_status_history (repair_job_id, new_status, changed_by) VALUES (?, 'Received', ?)")->execute([$new_id, $_SESSION['user_id']]);

                    // Record advance payment
                    if ($advance_payment > 0) {
                        $pdo->prepare("INSERT INTO payments (payment_type, reference_id, amount, payment_method, payment_date, received_by, notes) VALUES ('Repair',?,?,?,NOW(),?,?)")
                            ->execute([$new_id, $advance_payment, 'Cash', $_SESSION['user_id'], 'Advance payment']);
                    }

                    logActivity('Created Repair Job', 'Repairs', $new_id, "Job: $job_no");
                    $_SESSION['success'] = "Repair job $job_no created successfully.";
                }

                $pdo->commit();
                header('Location: repair_jobs.php'); exit;

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

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-<?= $edit_id ? 'edit' : 'plus' ?> me-2"></i><?= $edit_id ? 'Edit Repair Job' : 'New Repair Job Card' ?></h4>

        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <form method="POST">
            <input type="hidden" name="action" value="save_job">
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">Customer Information</div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">Customer *</label>
                                <select name="customer_id" class="form-select select2" required>
                                    <option value="">Select Customer</option>
                                    <?php foreach ($customers as $c): ?>
                                    <option value="<?= $c['id'] ?>" <?= ($job['customer_id'] ?? '') == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['name']) ?> (<?= htmlspecialchars($c['phone']) ?>)</option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Customer Notes</label>
                                <textarea name="customer_notes" class="form-control" rows="2"><?= htmlspecialchars($job['customer_notes'] ?? '') ?></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">Device Information</div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Brand</label>
                                    <input type="text" name="device_brand" class="form-control" value="<?= htmlspecialchars($job['device_brand'] ?? '') ?>" placeholder="e.g. Apple, Samsung">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Model</label>
                                    <input type="text" name="device_model" class="form-control" value="<?= htmlspecialchars($job['device_model'] ?? '') ?>" placeholder="e.g. iPhone 12">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">IMEI / Serial</label>
                                    <input type="text" name="imei_number" class="form-control" value="<?= htmlspecialchars($job['device_imei'] ?? '') ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Color</label>
                                    <input type="text" name="device_color" class="form-control" value="<?= htmlspecialchars($job['device_color'] ?? '') ?>">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header">Problem & Condition</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Problem Description *</label>
                            <textarea name="problem_description" class="form-control" rows="3" required><?= htmlspecialchars($job['problem_description'] ?? '') ?></textarea>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Device Condition Notes</label>
                            <textarea name="condition_notes" class="form-control" rows="3"><?= htmlspecialchars($job['device_condition'] ?? '') ?></textarea>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Password / Pattern Note (Optional)</label>
                            <input type="text" name="password_note" class="form-control" value="<?= htmlspecialchars($job['device_password_note'] ?? '') ?>" placeholder="e.g. Password: 1234">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Accessories Received</label>
                            <div class="row">
                                <?php $accs = ['Charger','Box','SIM Tray','Memory Card','Cover','Cable','Adapter','Other'];
                                $received = explode(',', $job['accessories_received'] ?? ''); ?>
                                <?php foreach ($accs as $a): ?>
                                <div class="col-4">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="acc_<?= $a ?>" value="<?= $a ?>" <?= in_array($a, $received) ? 'checked' : '' ?>>
                                        <label class="form-check-label"><?= $a ?></label>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <input type="hidden" name="accessories_received" id="accessories_received" value="<?= htmlspecialchars($job['accessories_received'] ?? '') ?>">
                        </div>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header">Pricing & Assignment</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Estimated Cost</label>
                            <input type="number" step="0.01" name="estimated_cost" class="form-control" value="<?= $job['estimated_cost'] ?? 0 ?>">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Advance Payment</label>
                            <input type="number" step="0.01" name="advance_payment" class="form-control" value="<?= $job['advance_payment'] ?? 0 ?>">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Labour Charge</label>
                            <input type="number" step="0.01" name="labour_charge" class="form-control" value="<?= $job['labour_charge'] ?? 0 ?>">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Expected Delivery</label>
                            <input type="date" name="expected_delivery_date" class="form-control" value="<?= $job['expected_delivery_date'] ?? '' ?>">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Assign Technician</label>
                            <select name="assigned_technician" class="form-select">
                                <option value="">Select Technician</option>
                                <?php foreach ($technicians as $t): ?>
                                <option value="<?= $t['id'] ?>" <?= ($job['assigned_technician_id'] ?? '') == $t['id'] ? 'selected' : '' ?>><?= htmlspecialchars($t['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Priority</label>
                            <select name="priority" class="form-select">
                                <option value="Normal" <?= ($job['priority'] ?? '') == 'Normal' ? 'selected' : '' ?>>Normal</option>
                                <option value="Urgent" <?= ($job['priority'] ?? '') == 'Urgent' ? 'selected' : '' ?>>Urgent</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <?php
                                $statuses = ['Received','Checking','Waiting for Customer Approval','Waiting for Parts','Repairing','Completed','Delivered','Cancelled','Cannot Repair'];
                                foreach ($statuses as $s):
                                ?>
                                <option value="<?= $s ?>" <?= ($job['repair_status'] ?? 'Received') == $s ? 'selected' : '' ?>><?= $s ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Internal Notes</label>
                        <textarea name="internal_notes" class="form-control" rows="2"><?= htmlspecialchars($job['internal_notes'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header d-flex justify-content-between">
                    <span><i class="fas fa-cogs me-1"></i>Spare Parts Used</span>
                    <button type="button" class="btn btn-sm btn-success" onclick="addPartRow()"><i class="fas fa-plus me-1"></i>Add Part</button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table no-datatable" id="partsTable">
                            <thead><tr><th>Spare Part</th><th>Qty</th><th>Selling Price</th><th>Total</th><th>Action</th></tr></thead>
                            <tbody>
                                <?php if (!empty($used_parts)): ?>
                                <?php foreach ($used_parts as $up): ?>
                                <tr>
                                    <td>
                                        <select name="parts_id[]" class="form-select select2">
                                            <option value="">Select</option>
                                            <?php foreach ($spare_parts as $sp): ?>
                                            <option value="<?= $sp['id'] ?>" <?= $up['product_id'] == $sp['id'] ? 'selected' : '' ?>><?= htmlspecialchars($sp['product_name']) ?> (Stock: <?= $sp['current_stock'] ?>)</option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="number" name="parts_qty[]" class="form-control" value="<?= $up['quantity'] ?>" min="1"></td>
                                    <td><input type="number" step="0.01" name="parts_price[]" class="form-control parts-price" value="<?= $up['selling_price'] ?>"></td>
                                    <td class="parts-total"><?= formatCurrency($up['total_price']) ?></td>
                                    <td><button type="button" class="btn btn-sm btn-danger remove-part"><i class="fas fa-times"></i></button></td>
                                </tr>
                                <?php endforeach; ?>
                                <?php else: ?>
                                <tr>
                                    <td>
                                        <select name="parts_id[]" class="form-select select2">
                                            <option value="">Select Spare Part</option>
                                            <?php foreach ($spare_parts as $sp): ?>
                                            <option value="<?= $sp['id'] ?>"><?= htmlspecialchars($sp['product_name']) ?> (Stock: <?= $sp['current_stock'] ?>)</option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="number" name="parts_qty[]" class="form-control" value="1" min="1"></td>
                                    <td><input type="number" step="0.01" name="parts_price[]" class="form-control parts-price" value="0"></td>
                                    <td class="parts-total">0.00</td>
                                    <td><button type="button" class="btn btn-sm btn-danger remove-part"><i class="fas fa-times"></i></button></td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="d-flex gap-2 mb-4">
                <button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-save me-1"></i><?= $edit_id ? 'Update' : 'Save' ?> Job Card</button>
                <a href="repair_jobs.php" class="btn btn-secondary btn-lg">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
function addPartRow() {
    var row = $('#partsTable tbody tr').first().clone();
    row.find('select').val('');
    row.find('input').val('1');
    $('.parts-total', row).text('0.00');
    $('#partsTable tbody').append(row);
    $('.select2').select2({ theme: 'bootstrap-5', width: '100%' });
}

$(document).on('click', '.remove-part', function() {
    if ($('#partsTable tbody tr').length > 1) {
        $(this).closest('tr').remove();
    }
});

$(document).on('input', '.parts-price, input[name="parts_qty[]"]', function() {
    var row = $(this).closest('tr');
    var qty = parseInt(row.find('input[name="parts_qty[]"]').val()) || 0;
    var price = parseFloat(row.find('.parts-price').val()) || 0;
    row.find('.parts-total').text((qty * price).toFixed(2));
});

// Collect accessories checkboxes
$(document).on('change', 'input[name^="acc_"]', function() {
    var vals = [];
    $('input[name^="acc_"]:checked').each(function() { vals.push($(this).val()); });
    $('#accessories_received').val(vals.join(','));
});
</script>

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