<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/database.php';

$database = new Database();
$db = $database->getConnection();
$auth = new Auth($database);

// Check permissions
if (!$auth->hasPermission('treasurer')) {
    header('Location: index.php');
    exit();
}

// Handle cash box operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_operation':
                $amount = $_POST['operation_type'] === 'deposit' ? $_POST['amount'] : -$_POST['amount'];
                
                // Add operation record
                $stmt = $db->prepare("
                    INSERT INTO cash_box_operations (
                        operation_type, amount, operation_date, 
                        description, reference_number, created_by
                    ) VALUES (?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $_POST['operation_type'],
                    abs($_POST['amount']), // Store absolute amount
                    $_POST['operation_date'],
                    $_POST['description'],
                    $_POST['reference_number'],
                    $_SESSION['user_id']
                ]);

                // Update cash box balance
                $db->prepare("
                    UPDATE cash_box 
                    SET current_balance = current_balance + ?,
                        last_updated = CURRENT_TIMESTAMP
                    WHERE id = 1
                ")->execute([$amount]);
                break;

            case 'edit_operation':
                if (isset($_POST['operation_id'])) {
                    // Get original operation
                    $stmt = $db->prepare("SELECT * FROM cash_box_operations WHERE id = ?");
                    $stmt->execute([$_POST['operation_id']]);
                    $original = $stmt->fetch(PDO::FETCH_ASSOC);

                    if ($original) {
                        // Calculate amounts
                        $original_amount = $original['operation_type'] === 'deposit' ? 
                            $original['amount'] : -$original['amount'];
                        $new_amount = $_POST['operation_type'] === 'deposit' ? 
                            $_POST['amount'] : -$_POST['amount'];

                        // Update operation
                        $stmt = $db->prepare("
                            UPDATE cash_box_operations 
                            SET amount = ?, operation_date = ?, description = ?, 
                                reference_number = ?, modified_by = ?, last_modified = CURRENT_TIMESTAMP
                            WHERE id = ?
                        ");
                        $stmt->execute([
                            abs($_POST['amount']),
                            $_POST['operation_date'],
                            $_POST['description'],
                            $_POST['reference_number'],
                            $_SESSION['user_id'],
                            $_POST['operation_id']
                        ]);

                        // Update cash box balance
                        $db->prepare("
                            UPDATE cash_box 
                            SET current_balance = current_balance - ? + ?,
                                last_updated = CURRENT_TIMESTAMP
                            WHERE id = 1
                        ")->execute([$original_amount, $new_amount]);
                    }
                }
                break;

            case 'delete_operation':
                if (isset($_POST['operation_id'])) {
                    // Get operation details before deletion
                    $stmt = $db->prepare("SELECT * FROM cash_box_operations WHERE id = ?");
                    $stmt->execute([$_POST['operation_id']]);
                    $operation = $stmt->fetch(PDO::FETCH_ASSOC);

                    if ($operation) {
                        // Calculate amount to reverse
                        $amount = $operation['operation_type'] === 'deposit' ? 
                            -$operation['amount'] : $operation['amount'];

                        // Update cash box balance
                        $db->prepare("
                            UPDATE cash_box 
                            SET current_balance = current_balance + ?,
                                last_updated = CURRENT_TIMESTAMP
                            WHERE id = 1
                        ")->execute([$amount]);

                        // Delete the operation
                        $db->prepare("DELETE FROM cash_box_operations WHERE id = ?")->execute([$_POST['operation_id']]);
                    }
                }
                break;
        }
        header('Location: index.php?page=cash_operations');
        exit();
    }
}

// Get cash box balance
$stmt = $db->query("SELECT * FROM cash_box WHERE id = 1");
$cash_box = $stmt->fetch(PDO::FETCH_ASSOC);

// Get recent operations
$stmt = $db->query("
    SELECT 
        co.*,
        u1.username as created_by_user,
        u2.username as modified_by_user
    FROM cash_box_operations co
    LEFT JOIN users u1 ON co.created_by = u1.id
    LEFT JOIN users u2 ON co.modified_by = u2.id
    ORDER BY co.operation_date DESC, co.id DESC
    LIMIT 50
");
$operations = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid">
    <!-- Cash Box Summary -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <h5 class="card-title">صندوق النقد</h5>
                    <h3 class="card-text"><?php echo number_format($cash_box['current_balance'], 2); ?> درهم</h3>
                    <button class="btn btn-light btn-sm mt-2" data-bs-toggle="modal" data-bs-target="#addOperationModal">
                        <i class="bi bi-plus-circle"></i> عملية جديدة
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Operations History -->
    <div class="card">
        <div class="card-header">
            <h5 class="card-title mb-0">سجل عمليات الصندوق</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>التاريخ</th>
                            <th>نوع العملية</th>
                            <th>المبلغ</th>
                            <th>الوصف</th>
                            <th>رقم المرجع</th>
                            <th>المستخدم</th>
                            <th>آخر تعديل</th>
                            <th>العمليات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($operations as $operation): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($operation['operation_date']); ?></td>
                                <td>
                                    <?php if ($operation['operation_type'] === 'deposit'): ?>
                                        <span class="badge bg-success">إيداع</span>
                                    <?php else: ?>
                                        <span class="badge bg-danger">سحب</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo number_format(abs($operation['amount']), 2); ?> درهم</td>
                                <td><?php echo htmlspecialchars($operation['description']); ?></td>
                                <td><?php echo htmlspecialchars($operation['reference_number']); ?></td>
                                <td><?php echo htmlspecialchars($operation['created_by_user']); ?></td>
                                <td>
                                    <?php if ($operation['last_modified']): ?>
                                        <?php echo htmlspecialchars($operation['modified_by_user']); ?>
                                        <br>
                                        <small class="text-muted">
                                            <?php echo date('Y-m-d H:i', strtotime($operation['last_modified'])); ?>
                                        </small>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-primary edit-operation" 
                                            data-id="<?php echo $operation['id']; ?>"
                                            data-type="<?php echo $operation['operation_type']; ?>"
                                            data-amount="<?php echo abs($operation['amount']); ?>"
                                            data-date="<?php echo $operation['operation_date']; ?>"
                                            data-description="<?php echo htmlspecialchars($operation['description']); ?>"
                                            data-reference="<?php echo htmlspecialchars($operation['reference_number']); ?>"
                                            data-bs-toggle="modal" 
                                            data-bs-target="#editOperationModal">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <button class="btn btn-sm btn-danger delete-operation"
                                            data-id="<?php echo $operation['id']; ?>"
                                            data-bs-toggle="modal" 
                                            data-bs-target="#deleteOperationModal">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Operation Modal -->
<div class="modal fade" id="addOperationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">عملية نقدية جديدة</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_operation">
                    
                    <div class="mb-3">
                        <label class="form-label">نوع العملية</label>
                        <select class="form-select" name="operation_type" required>
                            <option value="deposit">إيداع</option>
                            <option value="withdrawal">سحب</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">المبلغ</label>
                        <input type="number" step="0.01" class="form-control" name="amount" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">التاريخ</label>
                        <input type="date" class="form-control" name="operation_date" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">الوصف</label>
                        <input type="text" class="form-control" name="description">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">رقم المرجع</label>
                        <input type="text" class="form-control" name="reference_number">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary">إضافة</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Operation Modal -->
<div class="modal fade" id="editOperationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">تعديل العملية</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="edit_operation">
                    <input type="hidden" name="operation_id" id="edit_operation_id">
                    
                    <div class="mb-3">
                        <label class="form-label">نوع العملية</label>
                        <select class="form-select" name="operation_type" id="edit_operation_type" required>
                            <option value="deposit">إيداع</option>
                            <option value="withdrawal">سحب</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">المبلغ</label>
                        <input type="number" step="0.01" class="form-control" name="amount" id="edit_amount" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">التاريخ</label>
                        <input type="date" class="form-control" name="operation_date" id="edit_date" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">الوصف</label>
                        <input type="text" class="form-control" name="description" id="edit_description">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">رقم المرجع</label>
                        <input type="text" class="form-control" name="reference_number" id="edit_reference">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary">حفظ التغييرات</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Operation Modal -->
<div class="modal fade" id="deleteOperationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">حذف العملية</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>هل أنت متأكد من حذف هذه العملية؟ لا يمكن التراجع عن هذا الإجراء.</p>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="delete_operation">
                <input type="hidden" name="operation_id" id="delete_operation_id">
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-danger">حذف</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Set today's date as default for date inputs
    const today = new Date().toISOString().split('T')[0];
    $('input[type="date"]').val(today);
    
    // Handle edit operation modal
    $('.edit-operation').click(function() {
        const id = $(this).data('id');
        const type = $(this).data('type');
        const amount = $(this).data('amount');
        const date = $(this).data('date');
        const description = $(this).data('description');
        const reference = $(this).data('reference');
        
        $('#edit_operation_id').val(id);
        $('#edit_operation_type').val(type);
        $('#edit_amount').val(amount);
        $('#edit_date').val(date);
        $('#edit_description').val(description);
        $('#edit_reference').val(reference);
    });
    
    // Handle delete operation modal
    $('.delete-operation').click(function() {
        const id = $(this).data('id');
        $('#delete_operation_id').val(id);
    });
});
</script>
