<?php
// 1. Enable Error Reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 2. Database Connection
include 'db_connect.php'; 

// 3. Handle Notifications
$msg = "";
$msg_type = "";
if (isset($_GET['msg'])) {
    if ($_GET['msg'] == 'deleted') { $msg = "Contribution deleted successfully."; $msg_type = "success"; }
    elseif ($_GET['msg'] == 'updated') { $msg = "Contribution updated successfully."; $msg_type = "success"; }
    elseif ($_GET['msg'] == 'error') { 
        $reason = isset($_GET['reason']) ? $_GET['reason'] : '';
        $msg = ($reason == 'duplicate') ? "Error: Receipt Number already exists!" : "An error occurred."; 
        $msg_type = "danger"; 
    }
}

// 4. Validate Partner ID
$partner_id = isset($_GET['partner_id']) ? intval($_GET['partner_id']) : 0;
if ($partner_id === 0) {
    die("<div style='color:red; padding:20px; font-family:sans-serif;'><strong>Error:</strong> Invalid or missing Partner ID in the URL.</div>");
}

// 5. Set Filter Dates (Default to Current Month)
$filter_month = isset($_GET['filter_month']) ? $_GET['filter_month'] : date('Y-m');
$start_date = $filter_month . "-01";
$end_date = date("Y-m-t", strtotime($start_date));

// 6. Fetch Partner Details
$sql_partner = "SELECT * FROM Partners WHERE partner_id = ?";
$stmt = $conn->prepare($sql_partner);
$stmt->bind_param("i", $partner_id);
$stmt->execute();
$partner = $stmt->get_result()->fetch_assoc();
if (!$partner) {
    die("<div style='color:red; padding:20px; font-family:sans-serif;'><strong>Error:</strong> Partner not found.</div>");
}

// 7. Fetch Contributions
$sql_contribs = "
    SELECT fc.*, pa.agreement_code 
    FROM Financial_Contributions fc
    JOIN Partnership_Agreements pa ON fc.agreement_id = pa.agreement_id
    WHERE pa.partner_id = ? 
    AND fc.contribution_date BETWEEN ? AND ?
    ORDER BY fc.contribution_date DESC
";
$stmt_c = $conn->prepare($sql_contribs);
$stmt_c->bind_param("iss", $partner_id, $start_date, $end_date);
$stmt_c->execute();
$result_contribs = $stmt_c->get_result();
$contributions = [];
$total_month = 0;
while($row = $result_contribs->fetch_assoc()) {
    $contributions[] = $row;
    $total_month += $row['amount'];
}

// 8. Fetch Agreements Summary
$sql_agreements = "SELECT pa.*, pt.type_name,
    (SELECT SUM(amount) FROM Financial_Contributions fc WHERE fc.agreement_id = pa.agreement_id) as total_contributed
    FROM Partnership_Agreements pa
    JOIN Partnership_Types pt ON pa.partnership_type_id = pt.partnership_type_id
    WHERE pa.partner_id = ? ORDER BY pa.start_date DESC";
$stmt_a = $conn->prepare($sql_agreements);
$stmt_a->bind_param("i", $partner_id);
$stmt_a->execute();
$agreements_result = $stmt_a->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Partner: <?php echo htmlspecialchars($partner['partner_name']); ?></title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
        .card { border: none; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 20px; }
        .header-section { background: #007bff; color: white; padding: 30px 20px; border-radius: 0 0 20px 20px; margin-bottom: 30px; }
    </style>
</head>
<body>

<div class="header-section text-center">
    <h2><?php echo htmlspecialchars($partner['partner_name']); ?></h2>
    <p>Code: <?php echo htmlspecialchars($partner['partner_code'] ?? 'N/A'); ?></p>
</div>

<div class="container">
    
    <?php if ($msg): ?>
        <div class="alert alert-<?php echo $msg_type; ?> alert-dismissible fade show">
            <?php echo $msg; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
    <?php endif; ?>

    <div class="card p-3">
        <div class="row align-items-end">
            <div class="col-md-6">
                <form method="GET" action="" class="form-inline">
                    <input type="hidden" name="partner_id" value="<?php echo $partner_id; ?>">
                    <label class="mr-2 font-weight-bold">View Month:</label>
                    <input type="month" name="filter_month" class="form-control mr-2" value="<?php echo $filter_month; ?>" onchange="this.form.submit()">
                </form>
            </div>
            <div class="col-md-6 text-right">
                <form method="POST" action="individual_monthly_generate_pdf.php" target="_blank">
                    <input type="hidden" name="partner_id" value="<?php echo $partner_id; ?>">
                    <input type="hidden" name="filter_month" value="<?php echo $filter_month; ?>">
                    <button type="submit" class="btn btn-danger"><i class="fas fa-file-pdf"></i> Download PDF</button>
                </form>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0 text-primary font-weight-bold">Monthly Ledger: <?php echo date("F Y", strtotime($start_date)); ?></h5>
            <span class="badge badge-success p-2">Total: <?php echo number_format($total_month, 2); ?></span>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>Date</th>
                            <th>Agreement</th>
                            <th>Receipt #</th>
                            <th class="text-right">Amount</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($contributions) > 0): ?>
                            <?php foreach ($contributions as $row): ?>
                            <tr>
                                <td><?php echo $row['contribution_date']; ?></td>
                                <td><?php echo htmlspecialchars($row['agreement_code']); ?></td>
                                <td><?php echo htmlspecialchars($row['receipt_number'] ?? 'N/A'); ?></td>
                                <td class="text-right font-weight-bold"><?php echo number_format($row['amount'], 2); ?></td>
                                <td class="text-center">
                                    <button class="btn btn-sm btn-outline-primary" data-toggle="modal" data-target="#editModal<?php echo $row['contribution_id']; ?>">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <a href="contribution_actions.php?action=delete&id=<?php echo $row['contribution_id']; ?>&partner_id=<?php echo $partner_id; ?>" 
                                       class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this record?');">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </td>
                            </tr>
                            
                            <div class="modal fade" id="editModal<?php echo $row['contribution_id']; ?>" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form action="contribution_actions.php" method="POST">
                                            <div class="modal-header"><h5>Edit Contribution</h5></div>
                                            <div class="modal-body">
                                                <input type="hidden" name="action" value="update">
                                                <input type="hidden" name="contribution_id" value="<?php echo $row['contribution_id']; ?>">
                                                <input type="hidden" name="partner_id" value="<?php echo $partner_id; ?>">
                                                
                                                <div class="form-group">
                                                    <label>Receipt Number (Unique)</label>
                                                    <input type="text" name="receipt_number" class="form-control" value="<?php echo htmlspecialchars($row['receipt_number']); ?>" required>
                                                </div>

                                                <div class="form-group">
                                                    <label>Amount (<?php echo $row['currency']; ?>)</label>
                                                    <input type="number" step="0.01" name="amount" class="form-control" value="<?php echo $row['amount']; ?>" required>
                                                </div>

                                                <div class="form-group">
                                                    <label>Date</label>
                                                    <input type="date" name="contribution_date" class="form-control" value="<?php echo $row['contribution_date']; ?>" required>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                <button type="submit" class="btn btn-primary">Save Changes</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="5" class="text-center py-4 text-muted">No records found for this month.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>