<?php
session_start();
$nama_pegawai = $_SESSION['nama_pegawai'];

include '../koneksi.php';
if (isset($_POST["tambah"])) {

    $idtelp_custbisman = $_POST["idtelp_custbisman"];
    // echo "<br>";
    $tgl = $_POST["tgl_customer"];
    // echo "<br>";
    $bu = $_POST["bu"];
    $nama = $_POST["bu"] . $_POST["nama_customer"];
    // echo "<br>";
    $nama_customer = $_POST["nama_customer"];
    // $pic = $_POST["tt"] . " " . $_POST["pic"];
    // echo "<br>";
    $alamat = $_POST["alamat"];
    $telpe = $_POST["telp"];
    $telp = str_replace('-','',$telpe);
    // echo "<br>";
    // $tt = $_POST["tt"];
    $kota = $_POST["kota"];
    $email = $_POST["email"];
    $kebutuhan = $_POST["kebutuhan"];
    // echo "<br>";
    $keperluan = $_POST["keperluane"] ?? '';
    // echo "<br>";
    $status = $_POST['statuse'] ?? '';
    $tglhold = $_POST['tglhold'] ?? '';
    $note_telp = $_POST['note_telp'] ?? '';


    $sumber = $_POST["sumber"];
    // echo $keterangansumber = $_POST["keteranganSumberEmail"];

    if (empty($nama_customer)) {
        $query = mysqli_query($konek, "
            SELECT MAX(CAST(SUBSTRING(nama_customer, 5) AS UNSIGNED)) AS last_no
            FROM customeb
            WHERE nama_customer LIKE 'NULL%'");
        $dataNull = mysqli_fetch_assoc($query);

        $urutan = ($dataNull['last_no'] ?? 0) + 1;

        $nama_customer = 'NULL' . $urutan;
    }

    $map = [
        'Website' => 'keteranganSumberWeb',
        'WA' => 'keteranganSumberWA',
        'Email'   => 'keteranganSumberEmail',
        'Telp'    => 'keteranganSumberTelp'
    ];

    if (isset($map[$sumber])) {
        echo $ketarangansumber = $_POST[$map[$sumber]] ?? '';
    } else {
        $keterangansumber = '';
    }

    if (str_contains(strtolower($keperluan), 'service')) {
        $jenis_keperluan = 'service';
    } else if (str_contains(strtolower($keperluan), 'rental')) {
        $jenis_keperluan = 'rental';
    }else {
        $jenis_keperluan = 'penjualan';
    }

    $cekcust = mysqli_query($konek, "SELECT * FROM customeb WHERE nama_customer = '$nama_customer' AND alamat='$alamat' AND kota='$kota' AND bu='$bu'");

    if ($data = mysqli_num_rows($cekcust) > 0) {
        $caricus = mysqli_query($konek, "SELECT * FROM customeb WHERE nama_customer = '$nama_customer' AND alamat='$alamat' AND kota='$kota' AND bu='$bu'");
        $row = mysqli_fetch_array($caricus);
        $idcustomer = $row["idcustomer"];
    } else {
        $query = mysqli_query($konek, "
                SELECT MAX(idcustomer) AS last_id FROM customeb");
        $data = mysqli_fetch_assoc($query);

        $lastId = $data['last_id'];
        $urutan = (int) substr($lastId, 3, 5);
        $urutan++;

        $idcustomer = 'CUS' . str_pad($urutan, 5, '0', STR_PAD_LEFT);
        $tglinputcustomer = date('Y-m-d');

        $sqlmasuk = mysqli_query($konek, "INSERT INTO customeb VALUES ('$idcustomer','$bu','$nama_customer','$alamat','$kota','$telp','$email','$tglinputcustomer')");
    }

    $buatpenawaran = 0;
    $cektelp = mysqli_query($konek, "SELECT * FROM telp_custbisman WHERE idtelp_custbisman = '$idtelp_custbisman'");
    if (mysqli_num_rows($cektelp) == 0) {
        $sql = mysqli_query($konek, "INSERT INTO telp_custbisman VALUES ('$idtelp_custbisman','$tgl','$idcustomer','$keperluan','$kebutuhan','$jenis_keperluan','$sumber','$ketarangansumber','$buatpenawaran','$note_telp')");
    } else {
        $cektelp1 = mysqli_query($konek, "SELECT * FROM telp_custbisman WHERE idtelp_custbisman = '$idtelp_custbisman' AND idcustomer='$idcustomer'");
        if (mysqli_num_rows($cektelp1) == 1) {
            $idtelp_custbisman = $_POST["idtelp_custbisman"];
        } else {
            $query = mysqli_query($konek, "
            SELECT MAX(idtelp_custbisman) AS last_id FROM telp_custbisman");
            $data = mysqli_fetch_assoc($query);

            $lastId = $data['last_id']; // PGW005
            $urutan = (int) substr($lastId, 3, 5);
            $urutan++;

            echo $keterangansumber;
            $idtelp_custbisman = 'TCR' . str_pad($urutan, 5, '0', STR_PAD_LEFT);
            header("Location: ../telp_custbismantambah.php?idtelp_custbisman=$idtelp_custbisman");
            $sql = mysqli_query($konek, "INSERT INTO telp_custbisman VALUES ('$idtelp_custbisman','$tgl','$idcustomer','$keperluan','$sumber','$ketarangansumber','$note_telp')");
        }
    }


    //Follow Up
    $query = mysqli_query($konek, "
                SELECT MAX(idfollowup_bisman) AS last_id FROM followup_bisman");
    $data = mysqli_fetch_assoc($query);

    $lastId = $data['last_id'];
    $urutan = (int) substr($lastId, 3, 5);
    $urutan++;

    $idfollowup_bisman = 'FTR' . str_pad($urutan, 5, '0', STR_PAD_LEFT);
    $tglfllw = date('Y-m-d');

    if ($status == "Penawaran" || $status == "Closing" || $status == "Cancel") {
        $masukfollow = mysqli_query($konek, "INSERT INTO followup_bisman VALUES('$idfollowup_bisman','$tglfllw','$status','$tglfllw','','','$idtelp_custbisman')");
    } else if ($status == 'Hold') {
        $masukfollow = mysqli_query($konek, "INSERT INTO followup_bisman VALUES('$idfollowup_bisman','$tglfllw','$status','$tglfllw','$tglhold','','$idtelp_custbisman')");
    }

    //detail telp
    $query = mysqli_query($konek, "
                SELECT MAX(iddtelp_custbisman) AS last_id FROM telp_custbisman_detail");
    $data = mysqli_fetch_assoc($query);

    $lastId = $data['last_id'];
    $urutan = (int) substr($lastId, 3, 5);
    $urutan++;

    $iddetail_bismanps = 'TDR' . str_pad($urutan, 5, '0', STR_PAD_LEFT);
    // $sqle = mysqli_query($konek, "INSERT INTO telp_custbisman_detail VALUES('$iddetail_bismanps','$idtelp_custbisman','$sumber','$keterangansumber')");
    header("Location: ../telp_custbismantambah.php?idtelp_custbisman=$idtelp_custbisman&modal=ModalTmbTelp");
}
if (isset($_POST['edit'])) {
    // echo "Jiahaha";
    $idtelp_custbisman = $_POST["idtelp_custbisman"];
    $tgltelp_custbisman = $_POST["tgltelp_custbisman"];
    $keperluan = $_POST["keperluane"];
    $note = $_POST["note"];

    $sqledit = mysqli_query($konek, "UPDATE telp_custbisman SET tgltelp_custbisman='$tgltelp_custbisman',keperluan='$keperluan',note='$note' WHERE idtelp_custbisman='$idtelp_custbisman'");
    header("Location: ../telp_custbisman.php");
}
if (isset($_POST['tmbpic'])) {
    // echo "Jiahaha";
    echo $idtelp_custbisman = $_GET["idtelp_custbisman"];
    echo "<br>";
    echo $pic = $_POST['tt'] . " " . $_POST["pic"];
    echo "<br>";
    echo $telppice = $_POST["telppic"];
    $telppic = str_replace('-','',$telppice);
    $note = $_POST["note"];

    $cariidcus = mysqli_query($konek, "SELECT * FROM telp_custbisman WHERE idtelp_custbisman='$idtelp_custbisman'");
    $idcustomer = mysqli_fetch_array($cariidcus);
    $idcustomer = $idcustomer["idcustomer"];

    $cariidpice = mysqli_query($konek, "SELECT * FROM picb WHERE idcustomer='$idcustomer' AND nama_pic='$pic' AND telp_pic='$telppic'");
    $idpice = mysqli_num_rows($cariidpice);

    if ($idpice === 0) {
        $query = mysqli_query($konek, "
            SELECT MAX(idpic) AS last_id FROM picb");
        $data = mysqli_fetch_assoc($query);

        $lastId = $data['last_id']; // PGW005
        $urutan = (int) substr($lastId, 3, 5);
        $urutan++;

        echo $idpic = 'PIC' . str_pad($urutan, 5, '0', STR_PAD_LEFT);

        // $masukpic = mysqli_query($konek, "INSERT INTO picb VALUES('$idpic','$idcustomer','$pic','$telppic','$note')");
        if (empty($_POST["pic"])) {
            $masukpic = mysqli_query($konek, "INSERT INTO picb VALUES('$idpic','$idcustomer','$telppic','$telppic','$note')");
            }else{
            $masukpic = mysqli_query($konek, "INSERT INTO picb VALUES('$idpic','$idcustomer','$pic','$telppic','$note')");
        }
    } else {
        $cariidpic = mysqli_query($konek, "SELECT * FROM picb WHERE idcustomer='$idcustomer' AND nama_pic='$pic' AND telp_pic='$telppic'");
        $idpic = mysqli_fetch_assoc($cariidpic);
        echo $idpic = $idpic["idpic"] ?? '';
    }

    $query = mysqli_query($konek, "
            SELECT MAX(iddtelp_custbisman) AS last_id FROM telp_custbisman_detail");
    $data = mysqli_fetch_assoc($query);

    $lastId = $data['last_id']; // PGW005
    $urutan = (int) substr($lastId, 3, 5);
    $urutan++;

    $iddtelp_custbisman  = 'TDR' . str_pad($urutan, 5, '0', STR_PAD_LEFT);

    $masukdtelp = mysqli_query($konek, "INSERT INTO telp_custbisman_detail VALUES('$iddtelp_custbisman','$idtelp_custbisman','$idpic')");

    // $sqledit = mysqli_query($konek, "UPDATE telp_custbisman SET tgltelp_custbisman='$tgltelp_custbisman',keperluan='$keperluan',note='$note' WHERE idtelp_custbisman='$idtelp_custbisman'");
    // header("Location: ../telp_custbisman.php");
    if (isset($_GET['uedit'])) {
        header("Location: ../telp_custbismanedit.php?idtelp_custbisman=$idtelp_custbisman");
    } else {
        header("Location: ../telp_custbismantambah.php?idtelp_custbisman=$idtelp_custbisman");
    }
}
if (isset($_GET['hps'])) {
    $iddtelp_custbisman = $_GET['iddtelp_custbisman'];
    $idtelp_custbisman = $_GET['idtelp_custbisman'];

    $hps = mysqli_query($konek, "DELETE FROM telp_custbisman_detail WHERE iddtelp_custbisman = '$iddtelp_custbisman'");
    if (isset($_GET['uedit'])) {
        header("Location: ../telp_custbismanedit.php?idtelp_custbisman=$idtelp_custbisman");
    } else {
        header("Location: ../telp_custbismantambah.php?idtelp_custbisman=$idtelp_custbisman");
    }
}
if (isset($_POST['editpic'])) {
    $idtelp_custbisman = $_POST['idtelp_custbisman'];
    echo $idpic = $_POST['idpic'];
    echo $pic = $_POST['tt'] . " " . $_POST['pic'];
    echo $telp = $_POST['telp'];

    $editpic = mysqli_query($konek, "UPDATE pic SET nama_pic='$pic',telp_pic='$telp' WHERE idpic = '$idpic'");
    header("Location: ../telp_custbismanedit.php?idtelp_custbisman=$idtelp_custbisman");
}
if (isset($_POST['selesaiedit'])) {
    $idtelp_custbisman = $_POST["idtelp_custbisman"];
    $email = $_POST["email"];
    echo "<br>";
    $keperluan = $_POST["keperluane"] ?? '';
    echo "<br>";
    $note = $_POST["note"];
    $note_telp = $_POST["note_telp"];
    echo $sumber = $_POST["sumber"];

    $map = [
        'Website' => 'keteranganSumberWeb',
        'WA'   => 'keteranganSumberWA',
        'Email'   => 'keteranganSumberEmail',
        'Telp'    => 'keteranganSumberTelp'
    ];

    if (isset($map[$sumber])) {
        echo $ketarangansumber = $_POST[$map[$sumber]] ?? '';
    } else {
        $keterangansumber = '';
    }

    $edittelp = mysqli_query($konek, "UPDATE telp_custbisman SET keperluan='$keperluan',sumber='$sumber',ket_sumber='$ketarangansumber',note_telp='$note_telp' WHERE idtelp_custbisman = '$idtelp_custbisman'");
    header("Location: ../telp_custbisman.php");
}
if (isset($_GET['hpstelp'])) {
    $idtelp_custbisman = $_GET['idtelp_custbisman'];
    $tgl = $_GET['tgl'];

    $hps = mysqli_query($konek, "DELETE FROM followup_bisman WHERE idtelp_custbisman = '$idtelp_custbisman'");
    $hps = mysqli_query($konek, "DELETE FROM telp_custbisman_detail WHERE idtelp_custbisman = '$idtelp_custbisman'");
    $hps = mysqli_query($konek, "DELETE FROM telp_custbisman WHERE idtelp_custbisman = '$idtelp_custbisman'");
    header("Location: ../telp_custbisman.php");
}
if (isset($_POST['fllwup'])) {
    // echo $tgl = date('Y-m-d');
    // echo "<br>";
    echo $idtelp_custbisman = $_POST['idtelp_custbisman'];
    echo "<br>";
    echo $picada = $_POST['picada'];
    echo "<br>";
    echo $sttsfollowup = $_POST['sttsfollowup'];
    echo "<br>";
    echo $tglhold = $_POST['tglhold'];
    echo "<br>";
    echo $notefllw = $_POST['notefllw'];
    echo "<br>";
    $tgle = date('Y-m-d');
    $query = mysqli_query($konek, "
                SELECT MAX(idfollowup_bisman) AS last_id FROM followup_bisman");
    $data = mysqli_fetch_assoc($query);

    $lastId = $data['last_id'];
    $urutan = (int) substr($lastId, 3, 5);
    $urutan++;

    $idfollowup_bisman = 'FTR' . str_pad($urutan, 5, '0', STR_PAD_LEFT);
    if ($picada == 'ada') {
        $tglfllw = date('Y-m-d');
    } else {
        $cari = mysqli_query($konek, "SELECT * FROM followup_bisman WHERE idtelp_custbisman = '$idtelp_custbisman' AND idfollowup_bisman < '$idfollowup_bisman' ORDER BY idfollowup_bisman DESC LIMIT 1");
        $caris = mysqli_fetch_assoc($cari);
        $tglfllw = $caris["tglbisman_followup"];
    }
    $query = mysqli_query($konek, "INSERT INTO followup_bisman VALUES ('$idfollowup_bisman','$tgle','$sttsfollowup','$tglfllw','$tglhold','$notefllw','$idtelp_custbisman')");
    header("Location: ../telp_custbisman.php");
}
if (isset($_POST['buatpen'])) {
    echo $idtelp_custbisman = $_GET['idtelp_custbisman'];
    echo "<br>";
    echo $jpenawaran = $_POST['radiopen'];
    echo "<br>";
    echo $kota = $_POST['radiokot'];
    echo "<br>";

    if ($jpenawaran == "Penawaran Service"){
        header("Location: ../asset/autoid-penawaranbisman.php?radiokota=$kota&idtelp_custbisman=$idtelp_custbisman");
    }else{
        echo "<script>
            alert('Maaf!! Fitur ini masih dalam pengembangan!');
            window.location='../telp_custbisman.php';
          </script>";
    }
}
