<?php
session_start();
include '../../assets/constant/config.php';

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if (isset($_POST['submit'])) {


        $stmt = $conn->prepare("INSERT INTO `pledges`(`branch`,`member`,`campaign`, `pledges_amount`,`date`,`recurring`,`notes`) VALUES (?,?,?,?,?,?,?)");

        $stmt->execute([
           
            htmlspecialchars($_POST['branch'], ENT_QUOTES, 'UTF-8'),
            htmlspecialchars($_POST['member'], ENT_QUOTES, 'UTF-8'),
            htmlspecialchars($_POST['campaign'], ENT_QUOTES, 'UTF-8'),
            htmlspecialchars($_POST['pledges_amount'], ENT_QUOTES, 'UTF-8'),
            htmlspecialchars($_POST['date'], ENT_QUOTES, 'UTF-8'),
            htmlspecialchars($_POST['recurring'], ENT_QUOTES, 'UTF-8'),
           htmlspecialchars($_POST['notes'], ENT_QUOTES, 'UTF-8'),
        ]);

// Calculate and insert the total expense for the current branch
        $branch = htmlspecialchars($_POST['branch'], ENT_QUOTES, 'UTF-8');
        $stmt = $conn->prepare("UPDATE pledges SET total_pledges = (SELECT SUM(pledges_amount) FROM pledges WHERE branch = :branch) WHERE branch = :branch");
        $stmt->bindParam(':branch', $branch);
        $stmt->execute();

        $_SESSION['success'] = "success";

        header("location:../manage_pledges.php");
    }

    



// update pledges....

    if (isset($_POST['update'])) {

 $stmt = $conn->prepare("UPDATE `pledges` SET `branch`=?,`member`=?,`campaign`=?,`pledges_amount`=?,`date`=?, `recurring`=?,`notes`=? WHERE id=? ");
                  $stmt->execute([
            htmlspecialchars($_POST['branch'], ENT_QUOTES, 'UTF-8'),
            htmlspecialchars($_POST['member'], ENT_QUOTES, 'UTF-8'),
            htmlspecialchars($_POST['campaign'], ENT_QUOTES, 'UTF-8'),
            htmlspecialchars($_POST['pledges_amount'], ENT_QUOTES, 'UTF-8'),
            htmlspecialchars($_POST['date'], ENT_QUOTES, 'UTF-8'),
            htmlspecialchars($_POST['recurring'], ENT_QUOTES, 'UTF-8'),
           htmlspecialchars($_POST['notes'], ENT_QUOTES, 'UTF-8'),
           htmlspecialchars($_POST['id'], ENT_QUOTES, 'UTF-8')
        ]);
    
        $_SESSION['update'] = "update";
        header("location:../manage_pledges.php");
    }
    

    // delete pledges..

    if (isset($_POST['del_id'])) {

        $stmt = $conn->prepare("UPDATE `pledges` SET delete_status='1' where id=? ");

        $stmt->execute([htmlspecialchars($_POST['del_id'], ENT_QUOTES, 'UTF-8')]);

        $_SESSION['delete'] = "delete";

        header("location:../manage_pledges.php");
    }
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
