<?php
// edit_partnership.php

// Ensure this file points to your correct database connection file
// NOTE: db_connect.php must contain the mysqli connection object assigned to $conn
include 'db_connect.php'; 

error_reporting(E_ALL);
ini_set('display_errors', 1);


// Function to format phone numbers to start with "255"
function formatPhoneNumber($phone) {
    // Remove any non-digit characters except '+'
    $phone = preg_replace('/[^\d+]/', '', $phone);

    // If the number starts with '+255', replace it with '255'
    if (strpos($phone, '+255') === 0) {
        return '255' . substr($phone, 4);
    }
    // If the number starts with '0', replace it with '255'
    elseif (strpos($phone, '0') === 0) {
        return '255' . substr($phone, 1);
    }
    // If the number is 9 digits and doesn't start with 255 (e.g., 754xxxxxx), prepend 255
    elseif (strlen($phone) == 9 && strpos($phone, '255') !== 0) {
        return '255' . $phone;
    }
    // Otherwise, return the number as is (assuming it's already in the correct format)
    return $phone;
}

// Helper function to safely get data
function get_safe_data($key, $conn) {
    return isset($_POST[$key]) ? trim($_POST[$key]) : null;
}

// --- Fetch existing data based on ID ---
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("<div class='alert alert-danger m-3'>Invalid partner ID.</div>");
}

$partner_id = $_GET['id'];
$success_message = '';
$error_message = '';

$partner_data = [];
$agreement_data = [];
$commitment_data = []; 
$current_partnership_type = 'N/A';

// Fetch partner details
$stmt = $conn->prepare("SELECT * FROM Partners WHERE partner_id = ?");
$stmt->bind_param("i", $partner_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    $partner_data = $result->fetch_assoc();
    if (empty($partner_data['description'])) {
        $partner_data['description'] = 'N/A';
    }
} else {
    die("<div class='alert alert-danger m-3'>Partner not found.</div>");
}
$stmt->close();

// Fetch agreement details and active commitment
$stmt2 = $conn->prepare("
    SELECT pa.*, pt.type_name, pt.type_range, ach.commitment_amount, ach.commitment_currency, ach.commitment_frequency, ach.effective_start_date 
    FROM Partnership_Agreements pa 
    LEFT JOIN Partnership_Types pt ON pa.partnership_type_id = pt.partnership_type_id 
    LEFT JOIN Agreement_Commitment_History ach ON pa.agreement_id = ach.agreement_id AND ach.effective_end_date IS NULL
    WHERE pa.partner_id = ? 
    ORDER BY pa.created_at DESC LIMIT 1
");
$stmt2->bind_param("i", $partner_id);
$stmt2->execute();
$result2 = $stmt2->get_result();
if ($result2->num_rows > 0) {
    $agreement_data = $result2->fetch_assoc();
    $current_partnership_type = htmlspecialchars($agreement_data['type_name']);
    
    // Populate commitment data for the form display
    $commitment_data = [
        'commitment_amount' => $agreement_data['commitment_amount'] ?? '',
        'commitment_currency' => $agreement_data['commitment_currency'] ?? 'TZS',
        'commitment_frequency' => $agreement_data['commitment_frequency'] ?? 'Monthly',
        // Use effective_start_date from history, or agreement start_date as fallback
        'commitment_effective_date' => $agreement_data['effective_start_date'] ?? $agreement_data['start_date']
    ];
} else {
    // Default data if no agreement exists
    $agreement_data = [
        'agreement_id' => null,
        'partnership_type_id' => '',
        'start_date' => date('Y-m-d'), 
        'end_date' => null,  
        'status' => 'Active',
        'description' => 'Officially Approved'
    ];
    $commitment_data = [
        'commitment_amount' => '',
        'commitment_currency' => 'TZS',
        'commitment_frequency' => 'Monthly',
        'commitment_effective_date' => date('Y-m-d')
    ];
}
$stmt2->close();


// --- Handle form submission for UPDATE/INSERT ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Partner Details
    $partner_name = get_safe_data('partner_name', $conn);
    $contact_person = get_safe_data('contact_person', $conn);
    $is_organization = isset($_POST['is_organization']) ? 1 : 0;
    $member_id = $_POST['member_id'] ?: NULL;
    $phone1 = formatPhoneNumber(get_safe_data('phone_number1', $conn));
    $phone2 = formatPhoneNumber(get_safe_data('phone_number2', $conn));
    $email = get_safe_data('email_address', $conn);
    $address = get_safe_data('address', $conn);
    $desc = get_safe_data('partner_description', $conn);
    $loggedInUserId = 1; // Placeholder for the actual logged-in user ID

    // Agreement Details (NON-COMMITMENT fields)
    $agreement_id = $agreement_data['agreement_id'];
    $partnership_type_id = get_safe_data('partnership_type_id', $conn);
    $start_date = get_safe_data('start_date', $conn);
    $end_date = get_safe_data('end_date', $conn) ?: NULL;
    $agreement_desc = get_safe_data('agreement_description', $conn);
    $status = get_safe_data('status', $conn);

    // Commitment Details (NEW FIELDS FOR HISTORY)
    $new_commitment_amount = get_safe_data('commitment_amount', $conn) ?? '0.00'; 
    $new_commitment_currency = get_safe_data('commitment_currency', $conn);
    $new_commitment_frequency = get_safe_data('commitment_frequency', $conn);
    $new_commitment_effective_date = get_safe_data('commitment_effective_date', $conn); 

    // Input validation
    if (empty($partner_name) || empty($phone1) || empty($partnership_type_id) || empty($new_commitment_amount) || empty($new_commitment_currency) || empty($new_commitment_frequency) || empty($start_date) || empty($new_commitment_effective_date) || empty($status)) {
        $error_message = "Please fill in all required fields (Partner Name, Phone 1, Type, Commitment Amount, Effective Date, etc.).";
    } else {
        // Image upload and update logic
        $profile_image_url = $partner_data['profile_image_url'] ?? ''; 
        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] == 0) {
            $target_dir = "uploads/";
            if (!file_exists($target_dir)) {
                mkdir($target_dir, 0755, true);
            }
            $image_name = time() . '_' . basename($_FILES['profile_image']['name']);
            $target_file = $target_dir . $image_name;
            if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $target_file)) {
                $profile_image_url = $target_file;
                // Delete old image if it exists and is an uploaded file
                if (!empty($partner_data['profile_image_url']) && file_exists($partner_data['profile_image_url'])) {
                    if (strpos($partner_data['profile_image_url'], 'uploads/') === 0) {
                        @unlink($partner_data['profile_image_url']); 
                    }
                }
            } else {
                $error_message = "Error uploading new profile image.";
            }
        }

        if (empty($error_message)) {
            $conn->begin_transaction();
            try {
                // 1. Update Partner Table
                $stmt_update_partner = $conn->prepare("UPDATE Partners SET member_id=?, partner_name=?, contact_person_name=?, is_organization=?, phone_number1=?, phone_number2=?, email_address=?, address=?, description=?, profile_image_url=?, updated_by_user_id=?, updated_at=NOW() WHERE partner_id=?");
                if (!$stmt_update_partner) throw new Exception("Partner update prep failed: " . $conn->error);
                // 12 variables: i, s, s, i, s, s, s, s, s, s, i, i
                $stmt_update_partner->bind_param("ississssssii", $member_id, $partner_name, $contact_person, $is_organization, $phone1, $phone2, $email, $address, $desc, $profile_image_url, $loggedInUserId, $partner_id);
                if (!$stmt_update_partner->execute()) throw new Exception("Partner update failed: " . $stmt_update_partner->error);
                $stmt_update_partner->close();
 

                // 2. Update/Insert Partnership_Agreements Table
                if ($agreement_id) {
                    // Corrected SQL QUERY with updated_by_user_id
                    $sql_agreement_update = "UPDATE Partnership_Agreements SET partnership_type_id=?, start_date=?, end_date=?, status=?, description=?, updated_by_user_id=?, updated_at=NOW() WHERE agreement_id=?";
                    $stmt_update_agreement = $conn->prepare($sql_agreement_update);
                    if (!$stmt_update_agreement) throw new Exception("Agreement update prep failed: " . $conn->error);
                    
                    // Correct type string for 7 variables: "issssii" 
                    $stmt_update_agreement->bind_param("issssii", $partnership_type_id, $start_date, $end_date, $status, $agreement_desc, $loggedInUserId, $agreement_id);
                    
                    if (!$stmt_update_agreement->execute()) throw new Exception("Agreement update failed: " . $stmt_update_agreement->error);
                    $stmt_update_agreement->close();
                    
                    
                } else {
                    // Logic to insert new agreement if none exists 
                    $stmt_count = $conn->prepare("SELECT COUNT(*) as count FROM Partnership_Agreements");
                    $stmt_count->execute();
                    $result_count = $stmt_count->get_result();
                    $row_count = $result_count->fetch_assoc();
                    $agreement_count = $row_count['count'] + 1;
                    $agreement_code = 'AGR_' . str_pad($agreement_count, 6, '0', STR_PAD_LEFT);
                    $stmt_count->close();

                    $stmt_insert_agreement = $conn->prepare("INSERT INTO Partnership_Agreements (partner_id, partnership_type_id, start_date, end_date, status, description, created_by_user_id, agreement_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    if (!$stmt_insert_agreement) throw new Exception("New agreement insert prep failed: " . $conn->error);
                    // 8 Variables: i, i, s, s, s, s, i, s
                    $stmt_insert_agreement->bind_param("iissisis", $partner_id, $partnership_type_id, $start_date, $end_date, $status, $agreement_desc, $loggedInUserId, $agreement_code);
                    if (!$stmt_insert_agreement->execute()) throw new Exception("New agreement insert failed: " . $stmt_insert_agreement->error);
                    $agreement_id = $conn->insert_id; 
                    $stmt_insert_agreement->close();
                }

                // 3. Handle Commitment Update (Commitment History Logic)
                
                // Fetch the current active commitment for this agreement
                $sql_current_commitment = "SELECT commitment_history_id, commitment_amount, commitment_currency, commitment_frequency, effective_start_date FROM Agreement_Commitment_History WHERE agreement_id = ? AND effective_end_date IS NULL";
                $stmt_current = $conn->prepare($sql_current_commitment);
                if (!$stmt_current) throw new Exception("Current commitment query prep failed: " . $conn->error);
                $stmt_current->bind_param("i", $agreement_id);
                $stmt_current->execute();
                $result_current = $stmt_current->get_result();
                $current_commitment = $result_current->fetch_assoc();
                $stmt_current->close();

                // Get current values for comparison
                $current_commitment_amount_str = $current_commitment ? (string)$current_commitment['commitment_amount'] : '0.00';
                $current_commitment_frequency = $current_commitment['commitment_frequency'] ?? '';
                $current_effective_start_date = $current_commitment['effective_start_date'] ?? '';

                // Check if the commitment amount, frequency, or effective date has changed
                if (!$current_commitment || 
                    (string)$current_commitment_amount_str != $new_commitment_amount || 
                    $current_commitment_frequency != $new_commitment_frequency || 
                    ($new_commitment_effective_date && $current_effective_start_date != $new_commitment_effective_date)) 
                {
                    
                    $is_new_commitment_record_needed = true;

                    // A. END THE PREVIOUS COMMITMENT RECORD (If one exists)
                    if ($current_commitment) {
                        $prev_id = $current_commitment['commitment_history_id'];
                        
                        // Scenario 1: Only metadata (currency/frequency) changed, and amount/date is the same.
                        if ((string)$current_commitment_amount_str == $new_commitment_amount && $current_effective_start_date == $new_commitment_effective_date) {
                            // Update the existing active record instead of creating a new one
                            $sql_update_current = "UPDATE Agreement_Commitment_History SET commitment_currency=?, commitment_frequency=?, updated_by_user_id=? WHERE commitment_history_id=?";
                            $stmt_update_current = $conn->prepare($sql_update_current);
                            if (!$stmt_update_current) throw new Exception("Update current commitment prep failed: " . $conn->error);
                            $stmt_update_current->bind_param("ssii", $new_commitment_currency, $new_commitment_frequency, $loggedInUserId, $prev_id);
                            if (!$stmt_update_current->execute()) throw new Exception("Update current commitment failed: " . $stmt_update_current->error);
                            $stmt_update_current->close();
                            
                            $is_new_commitment_record_needed = false; 
                        } else {
                            // Scenario 2: Amount or Effective Date changed. Must create a new record.
                            // Validation: New effective date must be strictly AFTER the old start date.
                            if (strtotime($new_commitment_effective_date) <= strtotime($current_effective_start_date)) {
                                 throw new Exception("New commitment effective date (".$new_commitment_effective_date.") must be AFTER the current commitment's start date (".$current_effective_start_date.") when changing the amount.");
                            }
                            
                            // The end date is the day BEFORE the new effective date
                            $end_date_prev = date('Y-m-d', strtotime($new_commitment_effective_date . ' - 1 day'));
                            
                            $sql_end_prev = "UPDATE Agreement_Commitment_History SET effective_end_date = ?, updated_by_user_id = ? WHERE commitment_history_id = ?";
                            $stmt_end_prev = $conn->prepare($sql_end_prev);
                            if (!$stmt_end_prev) throw new Exception("End previous commitment prep failed: " . $conn->error);
                            $stmt_end_prev->bind_param("sii", $end_date_prev, $loggedInUserId, $prev_id);
                            if (!$stmt_end_prev->execute()) throw new Exception("End previous commitment failed: " . $stmt_end_prev->error);
                            $stmt_end_prev->close();
                            
                            $is_new_commitment_record_needed = true;
                        }

                    } else {
                        // Scenario 3: No current commitment exists (first time saving commitment for this agreement)
                        if ($agreement_id) {
                            $is_new_commitment_record_needed = true;
                        } else {
                            $is_new_commitment_record_needed = true;
                        }
                    }

                    // B. CREATE THE NEW COMMITMENT RECORD
                    if (isset($is_new_commitment_record_needed) && $is_new_commitment_record_needed) {
                        $sql_new_commit = "INSERT INTO Agreement_Commitment_History (agreement_id, commitment_amount, commitment_currency, commitment_frequency, effective_start_date, effective_end_date, created_by_user_id)
                                                VALUES (?, ?, ?, ?, ?, NULL, ?)"; 
                        $stmt_new_commit = $conn->prepare($sql_new_commit);
                        if (!$stmt_new_commit) throw new Exception("New commitment prep failed: " . $conn->error);
                        
                        // Bind parameters: i (id), s (amount - for DECIMAL precision), s (currency), s (frequency), s (date), i (user)
                        $stmt_new_commit->bind_param("issssi", $agreement_id, $new_commitment_amount, $new_commitment_currency, $new_commitment_frequency, $new_commitment_effective_date, $loggedInUserId);
                        
                        if (!$stmt_new_commit->execute()) throw new Exception("New commitment insert failed: " . $stmt_new_commit->error);
                        $stmt_new_commit->close();
                    }
                } 

                $conn->commit();
                $success_message = "Partnership details updated successfully!";

                // Re-fetch data to reflect changes immediately
                // Partner Data re-fetch
                $stmt = $conn->prepare("SELECT * FROM Partners WHERE partner_id = ?");
                $stmt->bind_param("i", $partner_id);
                $stmt->execute();
                $result = $stmt->get_result();
                $partner_data = $result->fetch_assoc();
                $stmt->close();
                
                // Agreement & Commitment Data re-fetch
                $stmt2 = $conn->prepare("
                    SELECT pa.*, pt.type_name, pt.type_range, ach.commitment_amount, ach.commitment_currency, ach.commitment_frequency, ach.effective_start_date 
                    FROM Partnership_Agreements pa 
                    LEFT JOIN Partnership_Types pt ON pa.partnership_type_id = pt.partnership_type_id 
                    LEFT JOIN Agreement_Commitment_History ach ON pa.agreement_id = ach.agreement_id AND ach.effective_end_date IS NULL
                    WHERE pa.partner_id = ? 
                    ORDER BY pa.created_at DESC LIMIT 1
                ");
                $stmt2->bind_param("i", $partner_id);
                $stmt2->execute();
                $result2 = $stmt2->get_result();
                if ($result2->num_rows > 0) {
                    $agreement_data = $result2->fetch_assoc();
                    $current_partnership_type = htmlspecialchars($agreement_data['type_name']);
                    // Re-populate commitment data for display
                    $commitment_data = [
                        'commitment_amount' => $agreement_data['commitment_amount'] ?? '',
                        'commitment_currency' => $agreement_data['commitment_currency'] ?? 'TZS',
                        'commitment_frequency' => $agreement_data['commitment_frequency'] ?? 'Monthly',
                        'commitment_effective_date' => $agreement_data['effective_start_date'] ?? $agreement_data['start_date']
                    ];
                }
                $stmt2->close();
                
            } catch (Exception $e) {
                $conn->rollback();
                $error_message = "Database update failed: " . $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Partnership</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; font-family: 'Inter', sans-serif; }
        .container { 
            background: white; 
            padding: 30px; 
            border-radius: 12px; 
            margin-top: 30px; 
            margin-bottom: 30px; 
            box-shadow: 0 4px 15px rgba(0,0,0,0.1); 
        }
        .section-title { 
            background: #e9ecef; 
            color: #333;
            padding: 10px 15px; 
            border-radius: 8px; 
            margin-bottom: 20px; 
            font-weight: bold; 
            border-left: 5px solid #007bff;
        }
        .image-preview {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border: 3px solid #007bff;
            border-radius: 50%; /* Circle shape for profile images */
            padding: 5px;
            /* Control display based on whether a file URL is present in the DB */
            display: <?php echo (!empty($partner_data['profile_image_url']) && file_exists($partner_data['profile_image_url'])) ? 'block' : 'none'; ?>;
            margin: 0 auto 10px;
        }
        .form-control, .form-select {
            border-radius: 8px;
        }
        .btn-primary {
            border-radius: 8px;
            padding: 10px 20px;
        }
        /* Loading Spinner Styles */
        .spinner-container {
            display: none; 
            position: fixed;
            z-index: 1050; 
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.6); 
            backdrop-filter: blur(2px); 
        }
        .loading-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            color: #ffffff;
        }
        .loading-content .spinner-border {
            width: 3rem;
            height: 3rem;
            border-width: 0.3em;
            color: #28a745; 
        }
        .loading-content p {
            margin-top: 15px;
            font-size: 1.2rem;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="spinner-container" id="loadingSpinner">
        <div class="loading-content">
            <div class="spinner-border text-success" role="status">
                <span class="visually-hidden">Updating...</span>
            </div>
            <p>Processing Update... Please Wait.</p>
        </div>
    </div>
    
    <div class="container">
        <div class="text-center mb-4">
            <h2 class="fw-bold text-primary">Update Partnership</h2>
            <p class="text-secondary">Editing details for: **<?php echo htmlspecialchars($partner_data['partner_name'] ?? 'Partner'); ?>**</p>
            <small class="text-muted">Partner ID: <?php echo htmlspecialchars($partner_data['partner_code'] ?? $partner_id); ?></small>
        </div>

        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger m-3 rounded-3"><?php echo $error_message; ?></div>
        <?php endif; ?>
        
        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success m-3 rounded-3 d-none" id="phpSuccessAlert"><?php echo $success_message; ?></div>
        <?php endif; ?>
        
        <form method="POST" enctype="multipart/form-data" id="updateForm">
            <div class="section-title">1. Partner Details</div>
            <div class="row g-3 mb-4">
                <div class="col-md-12 text-center">
                    <!-- Image Display Logic: Shows current image or a placeholder if none exists/is accessible -->
                    <img 
                        id="image_preview_box" 
                        src="<?php 
                            $image_path = $partner_data['profile_image_url'] ?? 'placeholder.png';
                            // Check if the file exists on the server. If not, use generic placeholder.
                            echo (file_exists($image_path) && !empty($partner_data['profile_image_url'])) ? htmlspecialchars($image_path) : 'https://placehold.co/150x150/e0e0e0/333333?text=No+Image'; 
                        ?>" 
                        alt="Profile Image" 
                        class="image-preview" 
                        style="display: block;" 
                        data-default-src="<?php echo (file_exists($image_path) && !empty($partner_data['profile_image_url'])) ? htmlspecialchars($image_path) : 'https://placehold.co/150x150/e0e0e0/333333?text=No+Image'; ?>"
                    >
                    <label class="form-label mt-2">Change Profile Image</label>
                    <input type="file" name="profile_image" class="form-control" id="profile_image_input" accept="image/*">
                </div>

                <div class="col-md-6">
                    <label class="form-label">Partner Name <span class="text-danger">*</span></label>
                    <input type="text" name="partner_name" class="form-control" value="<?php echo htmlspecialchars($partner_data['partner_name'] ?? ''); ?>" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Contact Person</label>
                    <input type="text" name="contact_person" class="form-control" value="<?php echo htmlspecialchars($partner_data['contact_person_name'] ?? ''); ?>">
                </div>
                
                <div class="col-md-3">
                    <label class="form-label">Is Organization?</label><br>
                    <div class="form-check form-switch pt-1">
                        <input class="form-check-input" type="checkbox" role="switch" name="is_organization" id="is_organization_switch" <?php echo ($partner_data['is_organization'] ?? 0 == 1) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_organization_switch">Yes</label>
                    </div>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Member ID (if applicable)</label>
                    <input type="number" name="member_id" class="form-control" value="<?php echo htmlspecialchars($partner_data['member_id'] ?? ''); ?>">
                </div>
                
                <div class="col-md-6">
                    <label class="form-label">Email Address</label>
                    <input type="email" name="email_address" class="form-control" value="<?php echo htmlspecialchars($partner_data['email_address'] ?? ''); ?>">
                </div>
                
                <div class="col-md-6">
                    <label class="form-label">Phone Number 1 <span class="text-danger">*</span></label>
                    <input type="text" name="phone_number1" class="form-control" value="<?php echo htmlspecialchars($partner_data['phone_number1'] ?? ''); ?>" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Phone Number 2</label>
                    <input type="text" name="phone_number2" class="form-control" value="<?php echo htmlspecialchars($partner_data['phone_number2'] ?? ''); ?>">
                </div>
                
                <div class="col-md-12">
                    <label class="form-label">Address</label>
                    <input type="text" name="address" class="form-control" value="<?php echo htmlspecialchars($partner_data['address'] ?? ''); ?>">
                </div>
                <div class="col-md-12">
                    <label class="form-label">Description (Partner)</label>
                    <textarea name="partner_description" class="form-control" rows="3"><?php echo htmlspecialchars($partner_data['description'] ?? ''); ?></textarea>
                </div>
            </div>

            <div class="section-title mt-4">2. Partnership Type & Agreement</div>
            <div class="row g-3 mb-4">
                <div class="col-md-6">
                    <label class="form-label">Current Type</label>
                    <input type="text" class="form-control-plaintext fw-bold" value="<?php echo $current_partnership_type; ?>" readonly>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Select New Partnership Type <span class="text-danger">*</span></label>
                    <select name="partnership_type_id" class="form-select" required>
                        <option value="">-- Select Type --</option>
                        <?php
                        // NOTE: Partnership_Types table query
                        $types = $conn->query("SELECT * FROM Partnership_Types");
                        if ($types) {
                            while ($row = $types->fetch_assoc()) {
                                $selected = (isset($agreement_data['partnership_type_id']) && $row['partnership_type_id'] == $agreement_data['partnership_type_id']) ? 'selected' : '';
                                echo "<option value='{$row['partnership_type_id']}' {$selected}>{$row['type_name']} ({$row['type_range']})</option>";
                            }
                        }
                        ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Agreement Start Date <span class="text-danger">*</span></label>
                    <input type="date" name="start_date" class="form-control" value="<?php echo htmlspecialchars($agreement_data['start_date'] ?? ''); ?>" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Agreement End Date (optional)</label>
                    <input type="date" name="end_date" class="form-control" value="<?php echo htmlspecialchars($agreement_data['end_date'] ?? ''); ?>">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Status <span class="text-danger">*</span></label>
                    <select name="status" class="form-select" required>
                        <?php
                        $statuses = ['Active', 'Completed', 'Lapsed', 'Cancelled'];
                        foreach ($statuses as $stat) {
                            $selected = ($stat == ($agreement_data['status'] ?? '')) ? 'selected' : '';
                            echo "<option value='{$stat}' {$selected}>{$stat}</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="col-md-12">
                    <label class="form-label">Agreement Description</label>
                    <textarea name="agreement_description" class="form-control" rows="3"><?php echo htmlspecialchars($agreement_data['description'] ?? ''); ?></textarea>
                </div>
            </div>

            <div class="section-title mt-4">3. Active Commitment History</div>
            <p class="text-muted small">Any change in Amount, Currency, Frequency, or Effective Date will generate a new commitment record in history.</p>
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Commitment Amount <span class="text-danger">*</span></label>
                    <input type="text" pattern="[0-9]*\.?[0-9]*" name="commitment_amount" class="form-control" value="<?php echo htmlspecialchars($commitment_data['commitment_amount'] ?? ''); ?>" required>
                </div>
                
                <div class="col-md-6">
                    <label class="form-label">Effective Date <span class="text-danger">*</span></label>
                    <input type="date" name="commitment_effective_date" class="form-control" value="<?php echo htmlspecialchars($commitment_data['commitment_effective_date'] ?? ''); ?>" required>
                </div>
                
                <div class="col-md-3">
                    <label class="form-label">Currency <span class="text-danger">*</span></label>
                    <input type="text" name="commitment_currency" class="form-control" value="<?php echo htmlspecialchars($commitment_data['commitment_currency'] ?? 'TZS'); ?>" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Frequency <span class="text-danger">*</span></label>
                    <select name="commitment_frequency" class="form-select" required>
                        <?php
                        $frequencies = ['Once', 'Monthly', 'Quarterly', 'Annually'];
                        foreach ($frequencies as $freq) {
                            $selected = ($freq == ($commitment_data['commitment_frequency'] ?? '')) ? 'selected' : '';
                            echo "<option value='{$freq}' {$selected}>{$freq}</option>";
                        }
                        ?>
                    </select>
                </div>
            </div>

            <div class="text-end mt-5 pt-3 border-top">
                <a href="index2.php?id=<?php echo $partner_id; ?>" class="btn btn-secondary me-2 rounded-pill">Cancel / Back</a>
                <a href="generate_pdf.php?id=<?php echo $partner_id; ?>" class="btn btn-info me-2 rounded-pill" target="_blank">Create PDF Document</a>
                <button type="button" class="btn btn-primary rounded-pill" id="updateBtn">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-save" viewBox="0 0 16 16">
                      <path d="M.5 1a.5.5 0 0 0 0 1h.5a.5.5 0 0 0 0-1z"/>
                      <path d="M8.5 6a.5.5 0 0 0-1 0v3.5l-3-3a.5.5 0 0 0-.854.354l3.5 3.5a.5.5 0 0 0 .708 0l3.5-3.5a.5.5 0 0 0-.854-.354l-3 3V6z"/>
                      <path d="M14 1a.5.5 0 0 0-.5-.5h-11a.5.5 0 0 0 0 1h11a.5.5 0 0 0 .5-.5zM3 3.5a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1 0-1h1a.5.5 0 0 1 .5.5z"/>
                      <path d="M12 2H4a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2zm-3 8a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"/>
                    </svg>
                    &nbsp; Save Changes
                </button>
            </div>
        </form>
    </div>

    <!-- Confirmation Modal -->
    <div class="modal fade" id="confirmModal" tabindex="-1" aria-labelledby="confirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content rounded-3 shadow-lg">
                <div class="modal-header bg-warning text-white">
                    <h5 class="modal-title" id="confirmModalLabel">⚠️ Confirm Partnership Update</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="lead">You are about to save changes for **<?php echo htmlspecialchars($partner_data['partner_name'] ?? 'Partner'); ?>**.</p>
                    <p>Please double-check all inputs. **A change in Commitment Amount or Effective Date will archive the current commitment and create a new historical record.**</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-warning rounded-pill" id="confirmUpdateBtn">Yes, Update Now</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Success Modal -->
    <div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content rounded-3 shadow-lg">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title" id="successModalLabel">✅ Success! Partnership Updated</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="lead">The details for **<?php echo htmlspecialchars($partner_data['partner_name'] ?? 'Partner'); ?>** have been successfully updated in the system.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-success rounded-pill" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const imageInput = document.getElementById('profile_image_input');
            const previewBox = document.getElementById('image_preview_box');
            const defaultSrc = previewBox.getAttribute('data-default-src');
            const updateBtn = document.getElementById('updateBtn');
            const confirmModal = new bootstrap.Modal(document.getElementById('confirmModal'));
            const confirmUpdateBtn = document.getElementById('confirmUpdateBtn');
            const loadingSpinner = document.getElementById('loadingSpinner');
            const successModal = new bootstrap.Modal(document.getElementById('successModal'));

            // --- Image Preview Logic ---
            imageInput.addEventListener('change', function(event) {
                const [file] = event.target.files;
                if (file) {
                    previewBox.src = URL.createObjectURL(file);
                    previewBox.style.display = 'block';
                } else {
                    // If file is cleared, revert to the image from the database (or the placeholder)
                    previewBox.src = defaultSrc;
                }
            });

            // --- Form Submission Logic ---

            // 1. Show confirmation modal on button click
            updateBtn.addEventListener('click', function() {
                confirmModal.show();
            });

            // 2. Submit form on confirmation, showing spinner
            confirmUpdateBtn.addEventListener('click', function() {
                // Hide confirmation modal
                confirmModal.hide();
                
                // Show amazing professional progress dialog
                loadingSpinner.style.display = 'block';

                // Submit the form
                document.getElementById('updateForm').submit();
            });

            // 3. Show success notification if PHP variable is set after successful postback
            <?php if (!empty($success_message)): ?>
                // Ensure the spinner is hidden (in case of fast submission)
                loadingSpinner.style.display = 'none';
                successModal.show();
            <?php endif; ?>
        });
    </script>
</body>
</html>