<?php
// add_Partnership.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Ensure db_connect.php exists
if (!file_exists('db_connect.php')) {
    die("Error: The 'db_connect.php' file was not found. Please ensure it's in the same directory.");
}
session_start();

// Include the database connection file (Assumed to define $conn)
include 'db_connect.php';

// Set logged-in user ID (Placeholder/Default to 1)
$loggedInUserId = 1; 

// --- HELPER FUNCTIONS ---

function getLocalSmsBalance($conn) {
    $sql = "SELECT current_balance FROM Kigango_SMS_Balance LIMIT 1";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return (int) $row['current_balance'];
    }
    return 0;
}

function updateSmsBalance($conn) {
    $sql = "UPDATE Kigango_SMS_Balance SET current_balance = current_balance - 1 WHERE current_balance > 0 LIMIT 1";
    return $conn->query($sql);
}

function logSms($conn, $logData) {
    // Check for existence of all necessary keys to prevent undefined index notice
    $logData = array_merge([
        'recipient_phone' => null, 'message_content' => null, 'sent_status' => null,
        'beem_request_id' => null, 'api_response' => null, 'sms_category_id' => null,
        'related_contribution_id' => null, 'authorized_person_id' => null,
        'partner_id' => null, 'partner_code' => null, 'monthYear' => null
    ], $logData);
    
    $stmt = $conn->prepare("INSERT INTO SMS_Log (recipient_phone, message_content, sent_status, beem_request_id, api_response, sms_category_id, related_contribution_id, authorized_person_id, partner_id, partner_code, monthYear) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    if ($stmt === false) {
        error_log("Prepare failed: " . $conn->error);
        return false;
    }

    $stmt->bind_param("sssssiisiss",
        $logData['recipient_phone'],
        $logData['message_content'],
        $logData['sent_status'],
        $logData['beem_request_id'],
        $logData['api_response'],
        $logData['sms_category_id'],
        $logData['related_contribution_id'],
        $logData['authorized_person_id'],
        $logData['partner_id'],
        $logData['partner_code'],
        $logData['monthYear']
    );

    $result = $stmt->execute();
    if ($result === false) {
        error_log("Execute failed: " . $stmt->error);
    }
    $stmt->close();
    return $result;
}

function generateUniquePartnerCode($conn) {
    do {
        $nextId = rand(100000, 999999);
        $partner_code = 'HP_' . $nextId;
        $stmt = $conn->prepare("SELECT partner_id FROM Partners WHERE partner_code = ?");
        $stmt->bind_param("s", $partner_code);
        $stmt->execute();
        $stmt->store_result();
    } while ($stmt->num_rows > 0);
    $stmt->close();
    return $partner_code;
}

function generateUniqueAgreementCode($conn) {
    do {
        $nextId = rand(100000, 999999);
        $agreement_code = 'AGR_' . $nextId;
        $stmt = $conn->prepare("SELECT agreement_id FROM Partnership_Agreements WHERE agreement_code = ?");
        $stmt->bind_param("s", $agreement_code);
        $stmt->execute();
        $stmt->store_result();
    } while ($stmt->num_rows > 0);
    $stmt->close();
    return $agreement_code;
}

function formatPhoneNumber($phone) {
    $phone = preg_replace('/[^\d+]/', '', $phone);
    if (strpos($phone, '+255') === 0) {
        return '255' . substr($phone, 4);
    } elseif (strpos($phone, '0') === 0) {
        return '255' . substr($phone, 1);
    }
    return $phone;
}

function sendSMSNotification($recipient, $message) {
    // API credentials and setup as provided in the original code
    $api_key = '4d2495c90cbee253'; 
    $secret_key = 'MWVkOWQzYWM5Yjg1MmNiNDA2ZGRiODZkODI3ZDQ0OTk4ODBmNzhmYTU5Mzg3YmM5Y2M5Y2ZkN2Q0OGI3ZTJlMw=='; 
    $source_addr = 'OCOAN';

    $postData = array(
        'source_addr' => $source_addr,
        'encoding' => 0,
        'schedule_time' => '',
        'message' => $message,
        'recipients' => [
            array(
                'recipient_id' => '1',
                'dest_addr' => $recipient
            )
        ]
    );

    $url = 'https://apisms.beem.africa/v1/send';

    $ch = curl_init($url);
    curl_setopt_array($ch, array(
        CURLOPT_POST => TRUE,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_HTTPHEADER => array(
            'Authorization:Basic ' . base64_encode("$api_key:$secret_key"),
            'Content-Type: application/json'
        ),
        CURLOPT_POSTFIELDS => json_encode($postData),
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0
    ));

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $responseData = json_decode($response, true);
    $result = [
        'status' => 'Failed',
        'beem_request_id' => null,
        'api_response' => $response,
        'error_message' => 'Unknown error.'
    ];

    if ($httpCode == 200 && isset($responseData['successful']) && $responseData['successful'] === true) {
        $result['status'] = 'Sent';
        $result['beem_request_id'] = $responseData['request_id'] ?? null;
        $result['error_message'] = null;
    } else {
        $result['error_message'] = 'HTTP Code ' . $httpCode . ' Response: ' . $response;
        error_log('Beem SMS API Error: ' . $result['error_message']);
    }

    return $result;
}
// --- END OF HELPER FUNCTIONS ---

$message = "";
$status = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    $partner_code = generateUniquePartnerCode($conn);
    $agreement_code = generateUniqueAgreementCode($conn);

    // --- Input Fetching ---
    $member_id = $_POST['member_id'] ?: NULL;
    $partner_name = $_POST['partner_name'];
    $contact_person = $_POST['contact_person'];
    $is_organization = isset($_POST['is_organization']) ? 1 : 0;
    
    $phone1 = formatPhoneNumber($_POST['phone_number1']);
    $phone2 = !empty($_POST['phone_number2']) ? formatPhoneNumber($_POST['phone_number2']) : NULL;
    
    $email = !empty($_POST['email_address']) ? $_POST['email_address'] : NULL;
    $address = $_POST['address'] ?: NULL;
    $desc = $_POST['partner_description'] ?: NULL;
    
    // Agreement and Commitment Details
    $partnership_type_id = $_POST['partnership_type_id'];
    $commitment_amount = floatval($_POST['commitment_amount'] ?? 0);
    $currency = $_POST['commitment_currency'];
    $frequency = $_POST['commitment_frequency'];
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'] ?: NULL;
    $agreement_desc = $_POST['agreement_description'] ?: NULL;
    $status_agreement = $_POST['status'];
    $created_by = $loggedInUserId;

    // Basic Validation Check
    if (empty($partner_name) || empty($phone1) || $commitment_amount <= 0 || empty($start_date)) {
        $_SESSION['message'] = "Missing required fields (Partner Name, Phone 1, Commitment Amount, or Start Date).";
        $_SESSION['status'] = "error";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }

    // --- Profile Image Upload ---
    $profile_image_url = 'uploads/default_profile.png';
    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;
        }
    }

    // --- Database Transaction ---
    $conn->begin_transaction();
    $partner_id = null; 
    $agreement_id = null;
    $success_flag = false; // Flag to check if all database steps succeeded

    try {
        // 1. Insert into Partners table
        $_SESSION['progress_step'] = 1; // For JS update
        $stmt = $conn->prepare("INSERT INTO Partners (partner_code, member_id, partner_name, contact_person_name, is_organization, phone_number1, phone_number2, email_address, address, description, profile_image_url, created_by_user_id, updated_by_user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        if (!$stmt) throw new Exception("Partner prep failed: " . $conn->error);
        
        // s, i, s, s, i, s, s, s, s, s, s, i, i (13 parameters)
        $stmt->bind_param("sississssssii", $partner_code, $member_id, $partner_name, $contact_person, $is_organization, $phone1, $phone2, $email, $address, $desc, $profile_image_url, $created_by, $created_by);
        
        if (!$stmt->execute()) throw new Exception("Partner insert failed: " . $stmt->error);
        $partner_id = $stmt->insert_id;
        $stmt->close();
        
        $_SESSION['step1_status'] = 'Partner record created successfully.';

        // 2. Insert into Partnership_Agreements table
        $_SESSION['progress_step'] = 2; // For JS update
        $sql_agreement = "INSERT INTO Partnership_Agreements (agreement_code, partner_id, partnership_type_id, start_date, end_date, status, description, created_by_user_id, updated_by_user_id) 
                             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; // 9 placeholders
        $stmt_agreement = $conn->prepare($sql_agreement);
        
        if (!$stmt_agreement) throw new Exception("Agreement prep failed: " . $conn->error);
        
        // FIX: Changed "siissssi" to "siissssii" to match 9 parameters (s, i, i, s, s, s, s, i, i)
        $stmt_agreement->bind_param("siissssii", $agreement_code, $partner_id, $partnership_type_id, $start_date, $end_date, $status_agreement, $agreement_desc, $created_by, $created_by);

        if (!$stmt_agreement->execute()) throw new Exception("Agreement insert failed: " . $stmt_agreement->error);
        $agreement_id = $stmt_agreement->insert_id;
        $stmt_agreement->close();
        
        $_SESSION['step2_status'] = 'Agreement header created successfully.';
        
        // 3. Insert into NEW Agreement_Commitment_History table
        $_SESSION['progress_step'] = 3; // For JS update
        $sql_commitment = "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_commitment = $conn->prepare($sql_commitment);
        
        if (!$stmt_commitment) throw new Exception("Commitment History prep failed: " . $conn->error);
        
        // FIX APPLIED: Changed 'd' (double) to 's' (string) for commitment_amount (decimal)
        // i, s, s, s, s, i (6 parameters)
        $stmt_commitment->bind_param("issssi", $agreement_id, $commitment_amount, $currency, $frequency, $start_date, $created_by);
        
        if (!$stmt_commitment->execute()) throw new Exception("Commitment History insert failed: " . $stmt_commitment->error);
        $stmt_commitment->close();

        // Commit transaction
        $conn->commit();
        $success_flag = true;
        
        $_SESSION['step3_status'] = 'Initial commitment saved successfully.';

        // --- SMS LOGIC ---
        $_SESSION['progress_step'] = 4; // For JS update
        $balance = getLocalSmsBalance($conn);
        $sms_message = "Nguvu ya Omega, ndugu {$partner_name}, umesajiliwa kwenye Haleluya TV partner na namba yako ni: {$partner_code}";
        $sms_status_message = "Partnership and Agreement saved successfully! ";
        $logStatus = 'Skipped';
        $logResponse = 'SMS sending skipped due to low local balance.';
        $send_result = ['beem_request_id' => null, 'api_response' => null];

        if ($balance < 1) {
            $sms_status_message .= "SMS notification failed due to low SMS balance. Please recharge.";
            $_SESSION['status'] = 'warning';
        } else {
            $send_result = sendSMSNotification($phone1, $sms_message);
            $logStatus = $send_result['status'];
            $logResponse = $send_result['api_response'];

            if ($send_result['status'] === 'Sent') {
                updateSmsBalance($conn);
                $sms_status_message .= "SMS sent to {$partner_name}.";
                $_SESSION['status'] = 'success';
            } else {
                $sms_status_message .= "SMS notification failed. " . ($send_result['error_message'] ?? 'Check API logs.');
                $_SESSION['status'] = 'warning';
            }
        }
        
        // Log the SMS attempt
        $logData = [
            'recipient_phone' => $phone1,
            'message_content' => $sms_message,
            'sent_status' => $logStatus,
            'beem_request_id' => $send_result['beem_request_id'],
            'api_response' => $logResponse,
            'sms_category_id' => 3,
            'related_contribution_id' => null,
            'authorized_person_id' => $created_by,
            'partner_id' => $partner_id,
            'partner_code' => $partner_code,
            'monthYear' => date('F Y')
        ];

        if (!logSms($conn, $logData)) {
            $sms_status_message .= " However, logging the SMS status failed.";
            if ($_SESSION['status'] != 'error') $_SESSION['status'] = 'warning';
        }
        
        $_SESSION['step4_status'] = 'SMS notification complete (Status: ' . $logStatus . ').';
        $_SESSION['message'] = $sms_status_message;


    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        $_SESSION['message'] = "Failed to save partnership. Database Error: " . $e->getMessage();
        $_SESSION['status'] = "error";
        error_log("Error adding partnership: " . $e->getMessage());
    }
    
    // Set a flag to trigger the final success/error dialog
    $_SESSION['process_finished'] = true;

    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    $status = $_SESSION['status'];
    unset($_SESSION['message']);
    unset($_SESSION['status']);
    
    // Check for intermediate statuses to display the progress dialog content
    $step1_status = isset($_SESSION['step1_status']) ? $_SESSION['step1_status'] : null;
    $step2_status = isset($_SESSION['step2_status']) ? $_SESSION['step2_status'] : null;
    $step3_status = isset($_SESSION['step3_status']) ? $_SESSION['step3_status'] : null;
    $step4_status = isset($_SESSION['step4_status']) ? $_SESSION['step4_status'] : null;
    $process_finished = isset($_SESSION['process_finished']) ? $_SESSION['process_finished'] : false;

    // Clear all step statuses after fetching them
    unset($_SESSION['step1_status'], $_SESSION['step2_status'], $_SESSION['step3_status'], $_SESSION['step4_status'], $_SESSION['progress_step'], $_SESSION['process_finished']);
}


$types = [];
// Re-establish connection only if needed for fetching types after redirect or if $conn was closed prematurely.
// Since it's in the main execution path, we must ensure $conn is available.
if (isset($conn) && $conn->ping()) {
    $types_result = $conn->query("SELECT * FROM Partnership_Types");
    if ($types_result) {
        while ($row = $types_result->fetch_assoc()) {
            $types[] = $row;
        }
    }
    // Close connection after fetching necessary data for the UI
    $conn->close();
}


?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Partnership</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; }
        .container { background: white; padding: 20px; border-radius: 12px; margin-top: 30px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
        .section-title { background: #e9ecef; padding: 10px 15px; border-radius: 8px; margin-bottom: 15px; font-weight: bold; }
        /* Progress Dialog Styles */
        .progress-dialog {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none; /* Hidden by default */
            justify-content: center;
            align-items: center;
            z-index: 1050;
        }
        .progress-content {
            background: white;
            padding: 30px;
            border-radius: 10px;
            text-align: center;
            width: 90%;
            max-width: 500px;
        }
        .progress-bar {
            transition: width 0.5s ease-in-out;
        }
    </style>
</head>
<body>

<div class="progress-dialog" id="progressDialog">
    <div class="progress-content">
        <h4>Processing Partnership...</h4>
        <div class="progress mb-3" style="height: 25px;">
            <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated bg-info" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
        </div>
        <p id="progressMessage">Starting...</p>
        <ul class="list-group list-group-flush text-start">
            <li class="list-group-item text-muted" id="step1_log">1. Creating Partner Record...</li>
            <li class="list-group-item text-muted" id="step2_log">2. Creating Agreement Header...</li>
            <li class="list-group-item text-muted" id="step3_log">3. Saving Initial Commitment...</li>
            <li class="list-group-item text-muted" id="step4_log">4. Sending SMS Notification...</li>
        </ul>
    </div>
</div>


<div class="container">
    <?php if (!empty($message)): ?>
        <div class="alert alert-<?php echo ($status === 'success') ? 'success' : (($status === 'warning') ? 'warning' : 'danger'); ?> m-3">
            <?php echo htmlspecialchars($message); ?>
            
            <?php if (!empty($step1_status) || !empty($step2_status)): ?>
            <hr>
            <h6>Process Summary:</h6>
            <ul class="list-unstyled mb-0">
                <li><strong>Partner:</strong> <?php echo htmlspecialchars($step1_status ?? 'N/A'); ?></li>
                <li><strong>Agreement:</strong> <?php echo htmlspecialchars($step2_status ?? 'N/A'); ?></li>
                <li><strong>Commitment:</strong> <?php echo htmlspecialchars($step3_status ?? 'N/A'); ?></li>
                <li><strong>SMS:</strong> <?php echo htmlspecialchars($step4_status ?? 'N/A'); ?></li>
            </ul>
            <?php endif; ?>
            
        </div>
    <?php endif; ?>
    
    <form method="POST" id="partnershipForm" enctype="multipart/form-data">
        <div class="section-title">1. Partner Details</div>
        <div class="row g-3">
            <div class="col-md-6">
                <label>Partner Name</label>
                <input type="text" name="partner_name" class="form-control" required>
            </div>
            <div class="col-md-6">
                <label>Contact Person</label>
                <input type="text" name="contact_person" class="form-control">
            </div>
            <div class="col-md-6">
                <label>Is Organization?</label><br>
                <input type="checkbox" name="is_organization">
            </div>
            <div class="col-md-6">
                <label>Member ID (if applicable)</label>
                <input type="number" name="member_id" class="form-control">
            </div>
            <div class="col-md-6">
                <label>Phone Number 1</label>
                <input type="text" name="phone_number1" class="form-control" required>
            </div>
            <div class="col-md-6">
                <label>Phone Number 2</label>
                <input type="text" name="phone_number2" class="form-control">
            </div>
            <div class="col-md-6">
                <label>Email Address</label>
                <input type="email" name="email_address" class="form-control">
            </div>
            <div class="col-md-6">
                <label>Address</label>
                <input type="text" name="address" class="form-control">
            </div>
            <div class="col-md-12">
                <label>Description</label>
                <textarea name="partner_description" class="form-control"></textarea>
            </div>
            <div class="col-md-12">
                <label>Profile Image</label>
                <input type="file" name="profile_image" class="form-control">
            </div>
        </div>
        <div class="section-title mt-4">2. Partnership Type</div>
        <div class="row">
            <div class="col-md-12">
                <label>Select Partnership Type</label>
                <select name="partnership_type_id" class="form-select" required>
                    <option value="">-- Select Type --</option>
                    <?php foreach ($types as $type): ?>
                        <option value="<?php echo htmlspecialchars($type['partnership_type_id']); ?>">
                            <?php echo htmlspecialchars($type['type_name'] . ' (' . $type['type_range'] . ')'); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <div class="section-title mt-4">3. Partnership Agreement</div>
        <div class="row g-3">
            <div class="col-md-6">
                <label>Commitment Amount</label>
                <input type="number" step="0.01" name="commitment_amount" class="form-control" required>
            </div>
            <div class="col-md-3">
                <label>Currency</label>
                <input type="text" name="commitment_currency" class="form-control" value="TZS" required>
            </div>
            <div class="col-md-3">
                <label>Frequency</label>
                <select name="commitment_frequency" class="form-select" required>
                    <option>Once</option>
                    <option selected>Monthly</option>
                    <option>Quarterly</option>
                    <option>Annually</option>
                </select>
            </div>
            <div class="col-md-6">
                <label>Start Date</label>
                <input type="date" name="start_date" class="form-control" required>
            </div>
            <div class="col-md-6">
                <label>End Date (optional)</label>
                <input type="date" name="end_date" class="form-control">
            </div>
            <div class="col-md-12">
                <label>Status</label>
                <select name="status" class="form-select" required>
                    <option value="Active" selected>Active</option>
                    <option value="Completed">Completed</option>
                    <option value="Lapsed">Lapsed</option>
                    <option value="Cancelled">Cancelled</option>
                </select>
            </div>
            <div class="col-md-12">
                <label>Agreement Description</label>
                <textarea name="agreement_description" class="form-control"></textarea>
            </div>
        </div>
        <div class="text-end mt-4">
            <button type="submit" class="btn btn-success">Submit Partnership</button>
        </div>
    </form>
</div>

<script>
    document.getElementById('partnershipForm').addEventListener('submit', function() {
        // Show progress dialog immediately upon submission
        document.getElementById('progressDialog').style.display = 'flex';
        
        // This is a simulated progress bar since the PHP uses a redirect.
        // In a real AJAX submission, you'd update this based on server responses.
        // Since we are using redirects, this bar serves as a general "working" indicator
        // that disappears on the next page load.
        var progress = 0;
        var interval = setInterval(function() {
            progress += 10;
            if (progress >= 90) {
                clearInterval(interval);
            }
            document.getElementById('progressBar').style.width = progress + '%';
            document.getElementById('progressBar').setAttribute('aria-valuenow', progress);
            document.getElementById('progressBar').innerText = progress + '%';
            document.getElementById('progressMessage').innerText = "Processing Data...";
        }, 300);
    });
</script>

</body>
</html>