<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user has permission (admin or operations)
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}

// Restrict access to admin and operations roles
if ($role_id != 1 && $role_id != 3) {
    $_SESSION['error_message'] = "You don't have permission to access this page.";
    header('Location: index.php');
    exit();
}

// Check if withdrawal ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "No withdrawal ID provided";
    header('Location: cheque_withdrawals.php');
    exit();
}

$withdrawal_id = intval($_GET['id']);

// Get withdrawal details
$sql = "
    SELECT 
        w.*,
        u1.full_name as requester_name
    FROM 
        cheque_withdrawals w
    LEFT JOIN 
        users u1 ON w.withdrawal_user_id = u1.user_id
    WHERE 
        w.id = ?
";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $withdrawal_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Withdrawal not found";
    header('Location: cheque_withdrawals.php');
    exit();
}

$withdrawal = $result->fetch_assoc();

// Check if withdrawal is pending and user is the creator or admin
if ($withdrawal['status'] !== 'pending') {
    $_SESSION['error_message'] = "This withdrawal request has already been " . $withdrawal['status'] . " and cannot be edited";
    header('Location: view_withdrawal.php?id=' . $withdrawal_id);
    exit();
}

if ($withdrawal['withdrawal_user_id'] != $user_id && $role_id != 1) {
    $_SESSION['error_message'] = "You don't have permission to edit this withdrawal request";
    header('Location: view_withdrawal.php?id=' . $withdrawal_id);
    exit();
}

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight Management System";
}

// Get banks list
$sql_banks = "SELECT id, bank_name FROM banks WHERE status = 'active' ORDER BY bank_name";
$result_banks = $conn->query($sql_banks);
$banks = [];
if ($result_banks && $result_banks->num_rows > 0) {
    while ($row = $result_banks->fetch_assoc()) {
        $banks[$row['id']] = $row['bank_name'];
    }
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $withdrawal_date = $_POST['withdrawal_date'];
    $currency = $_POST['currency'];
    $amount = $_POST['amount'];
    $purpose = $_POST['purpose'];
    $bank = $_POST['bank'];
    $bank_branch = $_POST['bank_branch'] ?? null;
    $cheque_number = $_POST['cheque_number'] ?? null;
    
    // Validate input
    $errors = [];
    
    if (empty($withdrawal_date)) {
        $errors[] = "Withdrawal date is required.";
    }
    
    if (empty($currency)) {
        $errors[] = "Currency is required.";
    }
    
    if (!is_numeric($amount) || $amount <= 0) {
        $errors[] = "Amount must be a positive number.";
    }
    
    if (empty($purpose)) {
        $errors[] = "Purpose is required.";
    }
    
    if (empty($bank)) {
        $errors[] = "Bank is required.";
    }
    
    // If no errors, update database
    if (empty($errors)) {
        try {
            // Get bank name from ID
            $bank_name = '';
            foreach ($banks as $id => $name) {
                if ($id == $bank) {
                    $bank_name = $name;
                    break;
                }
            }
            
            $sql = "UPDATE cheque_withdrawals SET 
                    withdrawal_date = ?, 
                    currency = ?, 
                    amount = ?, 
                    purpose = ?, 
                    bank = ?, 
                    bank_branch = ?, 
                    cheque_number = ? 
                    WHERE id = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param(
                'ssdssssi',
                $withdrawal_date,
                $currency,
                $amount,
                $purpose,
                $bank_name,
                $bank_branch,
                $cheque_number,
                $withdrawal_id
            );
            
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "Cheque withdrawal request updated successfully.";
                header('Location: view_withdrawal.php?id=' . $withdrawal_id);
                exit();
            } else {
                throw new Exception($stmt->error);
            }
        } catch (Exception $e) {
            $_SESSION['error_message'] = "Error updating withdrawal request: " . $e->getMessage();
        }
    } else {
        $_SESSION['error_message'] = implode("<br>", $errors);
    }
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Cheque Withdrawal')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Datepicker css -->
    <link rel="stylesheet" href="assets/libs/flatpickr/flatpickr.min.css">
    
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <style>
        .form-section {
            margin-bottom: 30px;
        }
        .form-section-title {
            border-bottom: 1px solid #e9e9ef;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        .required-field::after {
            content: "*";
            color: red;
            margin-left: 3px;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Finance Management', 'title' => 'Edit Cheque Withdrawal')); ?>

                    <?php
                    // Show success message if set
                    if (isset($_SESSION['success_message'])) {
                        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">';
                        echo $_SESSION['success_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['success_message']);
                    }
                    
                    // Show error message if set
                    if (isset($_SESSION['error_message'])) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $_SESSION['error_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['error_message']);
                    }
                    ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Edit Cheque Withdrawal #<?php echo $withdrawal_id; ?></h4>
                                </div>
                                <div class="card-body">
                                    <form action="" method="POST" id="withdrawal-form">
                                        <div class="form-section">
                                            <h5 class="form-section-title">Withdrawal Details</h5>
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label for="withdrawal_date" class="form-label required-field">Withdrawal Date</label>
                                                    <input type="text" class="form-control flatpickr-input" id="withdrawal_date" name="withdrawal_date" placeholder="YYYY-MM-DD" value="<?php echo $withdrawal['withdrawal_date']; ?>" required>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label for="currency" class="form-label required-field">Currency</label>
                                                    <select class="form-select" id="currency" name="currency" required>
                                                        <option value="">Select Currency</option>
                                                        <option value="USD" <?php echo $withdrawal['currency'] === 'USD' ? 'selected' : ''; ?>>USD</option>
                                                        <option value="Tsh" <?php echo $withdrawal['currency'] === 'Tsh' ? 'selected' : ''; ?>>Tsh</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label for="amount" class="form-label required-field">Amount</label>
                                                    <input type="number" class="form-control" id="amount" name="amount" step="0.01" min="0" placeholder="Enter amount" value="<?php echo $withdrawal['amount']; ?>" required>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label for="bank" class="form-label required-field">Bank</label>
                                                    <select class="form-select" id="bank" name="bank" required>
                                                        <option value="">Select Bank</option>
                                                        <?php 
                                                        foreach ($banks as $id => $name): 
                                                            $selected = ($name === $withdrawal['bank']) ? 'selected' : '';
                                                        ?>
                                                        <option value="<?php echo $id; ?>" <?php echo $selected; ?>><?php echo $name; ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label for="bank_branch" class="form-label">Bank Branch</label>
                                                    <input type="text" class="form-control" id="bank_branch" name="bank_branch" placeholder="Enter bank branch" value="<?php echo $withdrawal['bank_branch']; ?>">
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label for="cheque_number" class="form-label">Cheque Number</label>
                                                    <input type="text" class="form-control" id="cheque_number" name="cheque_number" placeholder="Enter cheque number" value="<?php echo $withdrawal['cheque_number']; ?>">
                                                </div>
                                                <div class="col-md-12 mb-3">
                                                    <label for="purpose" class="form-label required-field">Purpose</label>
                                                    <textarea class="form-control" id="purpose" name="purpose" rows="4" placeholder="Enter the purpose of withdrawal" required><?php echo $withdrawal['purpose']; ?></textarea>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="text-end">
                                            <a href="view_withdrawal.php?id=<?php echo $withdrawal_id; ?>" class="btn btn-secondary me-2">Cancel</a>
                                            <button type="submit" class="btn btn-primary">Update Request</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Datepicker js -->
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
    
    <!-- Sweet Alerts js -->
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize flatpickr date picker
            flatpickr("#withdrawal_date", {
                dateFormat: "Y-m-d",
                defaultDate: "<?php echo $withdrawal['withdrawal_date']; ?>"
            });
            
            // Form validation
            $('#withdrawal-form').on('submit', function(e) {
                var valid = true;
                
                // Check required fields
                $(this).find('[required]').each(function() {
                    if ($(this).val() === '') {
                        $(this).addClass('is-invalid');
                        valid = false;
                    } else {
                        $(this).removeClass('is-invalid');
                    }
                });
                
                // Check amount is positive
                var amount = $('#amount').val();
                if (amount <= 0) {
                    $('#amount').addClass('is-invalid');
                    valid = false;
                }
                
                if (!valid) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        text: 'Please fill all required fields and ensure amount is positive.',
                        confirmButtonColor: '#3085d6'
                    });
                }
            });
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>