<?php
session_start();
require_once 'includes/auth_helpers.php';
redirect_if_not_authenticated();
redirect_if_no_permission('edit_application');

require_once 'db/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit();
}

$customer_id = $_POST['customer_id'] ?? null;
if (!$customer_id) {
    die("Invalid request.");
}

$pdo = db();

// Handle File Upload
if (isset($_POST['upload_file'])) {
    if (isset($_FILES['file_upload']) && $_FILES['file_upload']['error'] === UPLOAD_ERR_OK) {
        $file_tmp_path = $_FILES['file_upload']['tmp_name'];
        $file_name = basename($_FILES['file_upload']['name']);

        // Sanitize filename
        $new_file_name = preg_replace('/[^a-zA-Z0-9-_. ]/', '', $file_name);
        $unique_file_name = time() . '-' . $new_file_name;
        $dest_path = 'uploads/' . $unique_file_name;

        if (move_uploaded_file($file_tmp_path, $dest_path)) {
            try {
                $sql = "INSERT INTO application_files (customer_application_id, filename, filepath) VALUES (?, ?, ?)";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$customer_id, $file_name, $unique_file_name]);
                $_SESSION['success_message'] = "File uploaded successfully.";
            } catch (PDOException $e) {
                $_SESSION['error_message'] = "Error saving file info: " . $e->getMessage();
            }
        } else {
            $_SESSION['error_message'] = "Error moving uploaded file.";
        }
    } else {
        $_SESSION['error_message'] = "Error uploading file: " . $_FILES['file_upload']['error'];
    }
    header("Location: edit_application.php?id=" . $customer_id);
    exit();
}

// Handle Form Submission
if (isset($_POST['save_changes'])) {
    try {
        $pdo->beginTransaction();

        // 1. Update Customer Table
        $sql = "UPDATE customer_applications SET 
                    company_name = ?,
                    company_website = ?,
                    company_phone = ?,
                    sales_owner = ?,
                    payment_terms = ?,
                    tags = ?,
                    notes = ?
                WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $_POST['company_name'],
            $_POST['company_website'],
            $_POST['company_phone'],
            $_POST['sales_owner'],
            $_POST['payment_terms'],
            $_POST['tags'],
            $_POST['notes'],
            $customer_id
        ]);

        // 2. Process Contacts
        $submitted_contact_ids = [];
        if (isset($_POST['contact']) && is_array($_POST['contact'])) {
            // Reset primary contact
            $reset_primary_stmt = $pdo->prepare("UPDATE customer_contacts SET is_primary = 0 WHERE customer_application_id = ?");
            $reset_primary_stmt->execute([$customer_id]);

            foreach ($_POST['contact'] as $index => $contact_data) {
                $contact_id = $contact_data['id'] ?? null;
                $is_primary = (isset($contact_data['is_primary']) && $contact_data['is_primary'] == '1') ? 1 : 0;

                if ($contact_id) { // Existing contact
                    $sql = "UPDATE customer_contacts SET name = ?, email = ?, phone = ?, is_primary = ? WHERE id = ? AND customer_application_id = ?";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([$contact_data['name'], $contact_data['email'], $contact_data['phone'], $is_primary, $contact_id, $customer_id]);
                    $submitted_contact_ids[] = $contact_id;
                } else { // New contact
                    $sql = "INSERT INTO customer_contacts (customer_application_id, name, email, phone, is_primary) VALUES (?, ?, ?, ?, ?)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([$customer_id, $contact_data['name'], $contact_data['email'], $contact_data['phone'], $is_primary]);
                    $submitted_contact_ids[] = $pdo->lastInsertId();
                }
            }
        }

        // 3. Delete Removed Contacts
        $stmt = $pdo->prepare("SELECT id FROM customer_contacts WHERE customer_application_id = ?");
        $stmt->execute([$customer_id]);
        $existing_contact_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
        $contacts_to_delete = array_diff($existing_contact_ids, $submitted_contact_ids);

        if (!empty($contacts_to_delete)) {
            $sql = "DELETE FROM customer_contacts WHERE id IN (" . implode(',', array_fill(0, count($contacts_to_delete), '?')) . ") AND customer_application_id = ?";
            $stmt = $pdo->prepare($sql);
            $params = array_merge(array_values($contacts_to_delete), [$customer_id]);
            $stmt->execute($params);
        }

        // 4. Process Addresses
        $submitted_address_ids = [];
        if (isset($_POST['address']) && is_array($_POST['address'])) {
            foreach ($_POST['address'] as $address_data) {
                $address_id = $address_data['id'] ?? null;

                if ($address_id) { // Existing address
                    $sql = "UPDATE customer_addresses SET address_type = ?, address_line_1 = ?, address_line_2 = ?, city = ?, state = ?, postal_code = ?, country = ? WHERE id = ? AND customer_application_id = ?";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([$address_data['type'], $address_data['line1'], $address_data['line2'], $address_data['city'], $address_data['state'], $address_data['postal_code'], $address_data['country'], $address_id, $customer_id]);
                    $submitted_address_ids[] = $address_id;
                } else { // New address
                    $sql = "INSERT INTO customer_addresses (customer_application_id, address_type, address_line_1, address_line_2, city, state, postal_code, country) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([$customer_id, $address_data['type'], $address_data['line1'], $address_data['line2'], $address_data['city'], $address_data['state'], $address_data['postal_code'], $address_data['country']]);
                    $submitted_address_ids[] = $pdo->lastInsertId();
                }
            }
        }

        // 5. Delete Removed Addresses
        $stmt = $pdo->prepare("SELECT id FROM customer_addresses WHERE customer_application_id = ?");
        $stmt->execute([$customer_id]);
        $existing_address_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
        $addresses_to_delete = array_diff($existing_address_ids, $submitted_address_ids);

        if (!empty($addresses_to_delete)) {
            $sql = "DELETE FROM customer_addresses WHERE id IN (" . implode(',', array_fill(0, count($addresses_to_delete), '?')) . ") AND customer_application_id = ?";
            $stmt = $pdo->prepare($sql);
            $params = array_merge(array_values($addresses_to_delete), [$customer_id]);
            $stmt->execute($params);
        }

        // Check if the application was reverted and resubmit it
        $stmt_status = $pdo->prepare("SELECT status FROM customer_applications WHERE id = ?");
        $stmt_status->execute([$customer_id]);
        $current_status = $stmt_status->fetchColumn();

        if ($current_status === 'REVERTED') {
            $stmt_resubmit = $pdo->prepare("UPDATE customer_applications SET status = 'pending_approval' WHERE id = ?");
            $stmt_resubmit->execute([$customer_id]);
            $_SESSION['message'] = "Application resubmitted for approval.";
            $_SESSION['message_type'] = 'success';
        } else {
            $_SESSION['message'] = "Application #{$customer_id} updated successfully.";
            $_SESSION['message_type'] = 'success';
        }
        
        $pdo->commit();

    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $_SESSION['message'] = "Error updating application: " . $e->getMessage();
        $_SESSION['message_type'] = 'danger';
    }

    header("Location: view_application.php?id=" . $customer_id);
    exit();
}

header("Location: index.php");
exit();